Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS memory allocation addresses

Quick curious question, memory allocation addresses are choosed by the language compiler or is it the OS which chooses the addresses for the memory asked?

This is from a doubt about virtual memory, where it could be quickly explained as "let the process think he owns all the memory", but what happens on 64 bits architectures where only 48 bits are used for memory addresses if the process wants a higher address?

Lets say you do a int a = malloc(sizeof(int)); and you have no memory left from the previous system call so you need to ask the OS for more memory, is the compiler the one who determines the memory address to allocate this variable, or does it just ask the OS for memory and it allocates it on the address returned by it?

like image 901
Cristiano Coelho Avatar asked Mar 11 '26 04:03

Cristiano Coelho


1 Answers

It would not be the compiler, especially since this is dynamic memory allocation. Compilation is done well before you actually execute your program.

Memory reservation for static variables happens at compile time. But the static memory allocation will happen at start-up, before the user defined Main.

Static variables can be given space in the executable file itself, this would then be memory mapped into the process address space. This is only one of few times(?) I can image the compiler actually "deciding" on an address.

During dynamic memory allocation your program would ask the OS for some memory and it is the OS that returns a memory address. This address is then stored in a pointer for example.

like image 163
Science_Fiction Avatar answered Mar 14 '26 09:03

Science_Fiction



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!