memory leak in dlopen / dlcose, or user error?

Calling dlopen then dlclose causes an increase in the amount of memory used by the program. If I create a loop that calls dlopen / dlclose repeatedly on the same dynamic library, memory usage increases continuously. Is this a bug, or am I using dlopen / dlclose incorrectly?

I can reproduce this by modifying the sample code in the Apple Developer docs Creating Dynamic Libraries. If I modify Runtime.c, changing the line void *lib_handle = dlopen(lib_name, RTLD_NOW); to add the infinite loop, as below:

void *lib_handle = dlopen(lib_name, RTLD_NOW);
for (int ii = 0; ; ++ii) {
    printf("loop %i\n", ii);
    int close_err = dlclose(lib_handle);
    printf("close error: %i\n", close_err);
    printf("dlopen(%s, RTLD_NOW)\n", lib_name);
    lib_handle = dlopen(lib_name, RTLD_NOW);
}

then opening and closing the dynamic library will succeed, but memory usage (as reported by top) will rapidly increase.

I'm running on x86_64 macOS 13.6.6. Full code for the modified Runtime.c is attached, the rest of the code is available in the Apple Developer docs.

Any suggestions?

Many thanks, Chris

I'm running on x86_64 macOS 13.6.6

Are you able to reproduce this on a more modern version of macOS?

There’s a couple of reasons why this matters:

  • The dynamic linker has received significant updates in the last few years, so it’s possible that this is fixed already.
  • If that’s the case, there’s no point filing a bug against macOS 13 because there’s no release vehicle for such a fix.

Notwithstanding the above, be aware that dlclose has a significant limitation on macOS: In many cases its unable to actually unload the library. This limitation is fundamental to the system, rather than a bug. The dlclose man page lists some of the causes, but those are just the start.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

memory leak in dlopen / dlcose, or user error?
 
 
Q