Static and Dynamic Memory Addresses in C

544 Views Asked by At
printf("address of literal: %p \n", "abc");
char alpha[] = "abcdef";
printf("address of alpha: %p \n", alpha);

Above, literal is stored in static memory, alpha is stored in dynamic memory. I read in a book that some compilers show these two addresses using different number of bits (I only tried using gcc on Linux, and it does show different number of bits). Does it depend on the compiler, or the operating system and hardware?

2

There are 2 best solutions below

0
On

alpha is stored e.g. in the stack or another dynamic memory segment. The literal is stored inside the code segment. These are different address ranges.

The addresses are platform dependant. In most cases the pointer size is 4 bytes long, but the addresses for the different segments are in different ranges.

The addresses are platform dependant.

The linker is responsible for the address assignment. You may want to enable an option to let the linker produce an address map file.

The dynamic parts are also called data segments. The static parts are code segments. You will find a lot literature searching for this term for your platform (e.g. search for "x86 memory segmentation").

0
On

I only tried using gcc on Linux, and it does show different number of bits

It's not that it "uses a different number of bits". As far as I know, Linux – at least when running the major platforms I know of (e.g. x86, x64, ARM32) – doesn't have "near" and "far" pointers. For instance, on x86, every pointer is 32 bits wide and on x64, every pointer is 64 bits wide.

It's just that…

  • the compiler probably allocates the alpha array on the stack (which it is allowed to do since it has automatic storage duration. It is most probably not stored in "dynamic memory", that would be stupid since that would involve a superfluous dynamic allocation, which is one of the slowest things you can do with memory.)
  • Meanwhile the literals themselves, having static storage duration, are stored elsewhere (usually in the data segment of the executable);
  • and on top of that, the OS's memory manager happens to place these two things (the stack and the executable image) far apart, so one of them has addresses that start with a lot of zeroes, while addresses in the other one don't have that many leading zeroes.
  • Furthermore, the default behavior of %p in your libc implementation happens to not print leading zeroes.