6
In a book about C, in which I started studying variables, it said that variables were randomly put into memory, for example:
int a;
int b;
printf("a = %d\n", &a); --> 5000 (endereço) (%d ao invés de %p para simplificar)
printf("b = %d\n", &b); --> 7634 (endereço) (%d ao invés de %p para simplificar)
However, from what I’ve researched, the local variables (i.e., within a function), they are in the stack, i.e., sequentially. And the global variables are randomly, i.e., in the heap. If I put one printf()
in local variables, they are in sequential addresses, as in this case (compiled by GCC on Linux):
char a;
int n;
float b;
printf("a = %p\n", &a); --> a = 0x7ffeb85afd5f
printf("n = %p\n", &n); --> n = 0x7ffeb85afd60
printf("b = %p\n", &b); --> b = 0x7ffeb85afd64
So this contradicts what I learned in the book. How to understand this?
What are and where are the "stack" and "heap"?
– UzumakiArtanis
Remember that not all architectures/platforms have the same type of memory management. A good example would be virtual memory management, which not all systems/ platforms have one! When the author says that variables are randomly placed in memory, means that who controls these addresses is the system/platform on which the code is being executed. These memory addresses are returned by the system and cannot be determined in a "portable". By the way, what is the publication date of the book you mentioned ?
– Lacobus
Book of 2007, called Linguagem C, by Luis Damas.
– Patrick Cardoso