Are variables allocated randomly in memory?

5

In a book about C, in which I started studying variables, I would say that the variables were randomly placed in 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 (ie, within a function), they stay in the stack , that is, sequentially. And the global variables are randomized, that is, in heap . If I put a printf() in the 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 do you understand this?

    
asked by anonymous 02.11.2017 / 22:16

1 answer

1

Randomly it is never the term, it always has a certain determinism, you just can not anticipate exactly where in the code, only at runtime.

And I'm going to talk about virtual memory , the physical memory is certainly organized in another way and things neither will be sequential physically, but it is not random, and this does not affect your code. Let's just do not care.

Before you make sure you understand the stack and heap a>.

Note that the C language does not dictate that this is the case, I will tell you how it actually works.

Do not use global variables. They are in a static area, which is not the heap , reserved by the compiler in advance.

Stack is a stack, so it's something sequential by definition. You do not have control where exactly it will be (you can check this at runtime, as you did in the question code), but it's far from random.

Heap is also not random, it has criteria, but it's a little more messy. It is a lot, so the organization leaves something to be desired, the goal is another. But it also does not spread throughout the memory without a sense. And some variables will be in sequence yes, especially in arrays . The organization just may not be so obvious.

The book may have simplified. Or you may have misinterpreted what was written. Or the book is really bad.

I made simplifications. It's a lot more complicated than that, but that's understandable.

    
02.11.2017 / 22:29