Static and dynamic memory addresses in C

advertisements
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?


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.