Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Why variables created in a loop have the same memory address?

Just a simple example of my problem:

while(condition){
    int number = 0;
    printf("%p", &number);
}

That variable will always be in the same memory address. Why?

And what's the real difference between declaring it inside or outside the loop then?

Would I need to malloc the variable every iteration to get different addresses?

like image 800
walkman Avatar asked Dec 01 '22 09:12

walkman


2 Answers

That variable will always be in the same memory address. Why?

It's not required to, but your code is so simple that it probably will be across all platforms. Specifically, because it's stored on the stack, it's always in the same place relative to your stack pointer. Keep in mind you're not allocating memory here (no new or malloc), you're just naming existing (stack-relative) memory.

And what's the real difference between declaring it inside or outside the loop then?

In this case, scope. The variable doesn't exist outside the braces where it lives in. Also outside of the braces, another variable can take its place if it fits in memory and the compiler chooses to do this.

Would I need to malloc the variable every iteration to get different addresses?

Yes, but I have yet to see a good use of malloc to allocate space for an int that a simple stack variable or a standard collection wouldn't do better.

like image 63
Blindy Avatar answered Jan 04 '23 22:01

Blindy


That variable will always be in the same memory address. Why?

The compiler decides where the variable should be, given the operating system constraints, it's much more efficient to maintain the variable at the same address than having it relocated at every iteration, but this could, theoretically, happen.

You can't rely on it being in the same address every time.

And what's the real difference between declaring it inside or outside the loop then?

The difference is lifetime of the variable, if declared within the loop it will only exist inside the loop, you can't access it after the loop ends.

When execution of the block ends the lifetime of the object ends and it can no longer be accessed.

Would I need to malloc the variable every iteration to get different addresses?

malloc is an expensive operation, it does not make much sense to malloc the variable at every iteration, that said, again, the compiler decides where the memory for it is allocated, it may very well be at the same address or not.

Once again you can't rely on the variable location in the previous iteration to assert where it will be on the next one.

There is a difference in the the variables are stored, allocated variables will be on the heap, as opposed to the stack like in the previous case.

like image 26
anastaciu Avatar answered Jan 05 '23 00:01

anastaciu