Vanuan
Vanuan

Reputation: 33442

Is it safe to call dlclose(NULL)?

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?

Upvotes: 6

Views: 2032

Answers (3)

user877329
user877329

Reputation: 6220

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.

Upvotes: 1

Talya
Talya

Reputation: 19347

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.

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363707

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.]

Upvotes: 5

Related Questions