Is it safe to call dlclose(NULL)?

怎甘沉沦 提交于 2021-02-05 02:52:52

问题


I experience a crash when I pass a null pointer to dlclose.

Should I check for null before calling dlclose?

POSIX tells nothing about this: http://pubs.opengroup.org/onlinepubs/7908799/xsh/dlclose.html

Is it undefined behaviour or a bug in dlclose implementation?


回答1:


This is tricky. POSIX states that

if handle does not refer to an open object, dlclose() returns a non-zero value

from which you could infer that it should detect, for an arbitrary pointer, whether that pointer refers to an open object. The Linux/Glibc version apparently does no such check, so you'll want to check for NULL yourself.

[Aside, the Linux manpage isn't very helpful either. It's quite implicit about libdl functions' behavior, deferring to POSIX without very clearly claiming conformance.]




回答2:


It also says nothing about being accepting a NULL and not crashing. We can assume from your test that it doesn't do an explicit NULL check, and it does need to use the pointer somehow to perform the closing action … so there you have it.




回答3:


Following the malloc/free convention (1), it is a bug. If it follows the fopen/fclose convention (2) it is not. So if there is a bug, it is in the standard because it lacks convention for dealing with zombies.

  • Convention (1) works well with C++11 move semantics
  • Convention (2) leaves more responsibility to the caller. In particular, a dtor must explicitly check for null if a move operation has been done.

I think this is something that should be revised for an upcoming POSIX revision in order to avoid confusion.


Update

I found from this answer https://stackoverflow.com/a/6277781/877329, and then reading man pthread_join that you can call pthread_join with an invalid tid, supporting the malloc/free convension. Another issue I have found with the dynamic loader interface is that it does not use the standard error handling system, but has its own dlerrorfunction.



来源:https://stackoverflow.com/questions/11412943/is-it-safe-to-call-dlclosenull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!