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

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