Luke4211
Luke4211

Reputation: 49

When are shared library functions loaded into the heap?

(This question concerns only the logical addresses)

I was experimenting with some code where I print out the addresses of different types/scopes of variables to better visualize the process image.

My confusion arose when I printed the addresses a few variables that have been allocated on the heap by malloc, and then also printed the address of the printf function out of curiosity.

What I discovered is that printf was being stored at a much higher address (ie closer to the stack) on the heap than my malloc allocated variables. This doesn't make sense to me because I assumed that the library functions would be loaded on the heap first thing at runtime before any other instructions are executed. I even put a printf statement before any malloc statements, in case library functions were loaded on the fly as they were needed, but it didn't change anything.

Thanks.

Upvotes: 1

Views: 414

Answers (1)

zwol
zwol

Reputation: 140639

(This answer concerns Unix only. I don't know how it is on Windows.)

Most shared libraries are loaded into RAM before control reaches main, and the library containing printf definitely will be. The functions in dlfcn.h can be used to load more shared libraries during execution of the program, that's the most important exception.

Shared libraries have never been loaded as part of the "heap", if by that you mean the region of memory used to satisfy malloc requests. They are loaded using the system primitive mmap, and could be placed anywhere at all in memory. As user3386109 pointed out in a comment on the question, on modern systems, their locations are intentionally randomized as a countermeasure for various exploits.

Upvotes: 4

Related Questions