开发者

Same memory space being allocated again & again

开发者 https://www.devze.com 2022-12-23 13:12 出处:网络
In each loop iteration, variable j is declared again and again. Then why is its address remaining same?

In each loop iteration, variable j is declared again and again. Then why is its address remaining same?

  • Shouldn't it be given some random address each time?
  • Is this compiler dependent?
#include<stdio.h>
#include<mall开发者_开发知识库oc.h>

int main()
{
    int i=3;
    while (i--)
    {
        int j;
        printf("%p\n", &j);
    }
    return 0;
}

Testrun:-

shadyabhi@shadyabhi-desktop:~/c$ gcc test.c
shadyabhi@shadyabhi-desktop:~/c$ ./a.out
0x7fffc0b8e138
0x7fffc0b8e138
0x7fffc0b8e138
shadyabhi@shadyabhi-desktop:~/c$


It is memory on the stack. It is not allocated from the heap. The stack would not change in that loop.


The reason why the address of j never changes is because the compiler allocates memory for j on the stack when the function is entered as opposed to when j comes into scope.

As always, looking at some assembly code might help explain the concept. Take the following function:-

int foo(void)
   {
   int i=3;
   i++;
      {
      int j=2;
      i=j;
      }
   return i;
   }

gcc converts this to the following x86 assembly code:-

foo:
    pushl   %ebp                 ; save stack base pointer
    movl    %esp, %ebp           ; set base pointer to old top of stack
    subl    $8, %esp             ; allocate memory for local variables
    movl    $3, -4(%ebp)         ; initialize i
    leal    -4(%ebp), %eax       ; move address of i into eax
    incl    (%eax)               ; increment i by 1
    movl    $2, -8(%ebp)         ; initialize j
    movl    -8(%ebp), %eax       ; move j into accumulator
    movl    %eax, -4(%ebp)       ; set i to j
    movl    -4(%ebp), %eax       ; set the value of i as the function return value
    leave                        ; restore stack pointers
    ret                          ; return to caller

Let's walk through this assembly code. The first line saves the current stack base pointer so that it can be restored when the function exits, the second line sets the current top of the stack to be the new stack base pointer for this function.

The third line is the one that allocates the memory on the stack for all the local variables. The instruction subl $8, %esp subtracts 8 from the current top of the stack pointer, the esp register. Stacks grow down in memory so this line of code actually increases the memory on the stack by 8 bytes. We have two integers in this function, i and j, each of which require 4 bytes, hence why it allocates 8 bytes.

Line 4 initializes i to 3 by directly writing to an address on the stack. Lines 5 and 6 then load and increment i. Line 7 initializes j by writing the value 2 into the memory allocated for j on the stack. Note that when j came into scope at line 7 the assembly code did not adjust the stack to allocate memory for it, that had already been taken care of earlier.

I'm sure it's obvious, but the reason why the compiler allocates the memory for all the local variables at the start of the function is because it is way more efficient to do so. Adjusting the stack each time a local variable went in or out of scope would result in a lot of unnecessary manipulations of the stack pointer for no gain.

I'm sure you can work out what the rest of the assembly code does yourself, if not post a comment and I'll walk you through it.


Why should it be different? The compiler needs space on the stack to store an int, and each time it goes through the loop the same space is available.

By the way, you're not actually using malloc at all. j is kept on the stack.


j and i are allocated on the stack, not on the heap or freestore (which would require a malloc or new, respectively). The stack puts the next variable in a deterministic location (the top of the stack), and so it always has the same address. Though if you are running in optimized mode, the variable is probably never "dealloced", that is, the stack size isn't changing throughout your program, because it would just be wasted cycles.


j is allocated on the stack, so during one call of that function, it will always have the same address.

If you called main() from within that loop, the "inner" main's j would have a different address, as it would be higher on the stack.

See Hardware Stack on Wikipedia for more details.


Actually you are not using malloc so what's the problem?

The variable is a local to the function, and its space is reserved on the stack during compilation.. so why should it reallocate it on every iteration? Just because it's declared inside the loop?


You are not malloc-ing. Its an stack address so its the same always because its always in the same place of the stack once and again.


It is declared within the loop as you say, but it both goes out of scope and is 'destroyed' at the end of each iteration (that is it is not in scope and does not exist when the loop condition is tested). Therefore it is perfectly legitimate for the same stack location to be reused (in fact it would be an error if this were not the case).


Hint: What do you think this will do?

#include<stdio.h>
#include<malloc.h>

int main()
{
    int i=3;
    while (i--)
    {
        int j = 42;
        printf("%p\n", &j);
    }
    return 0;
}


As other answers have said, you're not allocing here anything but on stack. But even if you modify code as follows, it will not necessarily change the allocation address.

This depends on libc that is used, malloc is usually located there, but some applications (most notably firefox) override it for their use (memory fragmentation issues etc.).

#include<stdio.h>
#include<malloc.h>

int main()
{
    int i=3;
    while (i--)
    {
        int *j = (int *) malloc(sizeof(int));
        printf("%p\n", j);
        free (j);
    }
    return 0;
}

if you comment out the free(j) you'll note that j's address does change. But depending on your libc the j's address may always change.


Now, you'd get a series of leaked allocations since the j's are not stored for subsequent free's. j wouldn't necesserily get random address but probably just as a sequence compared to the previous allocations of j.

If you would free j in the end of the loop, you could get the same behavior as before depending on the implementation of malloc and free.

Edit: you may want to recheck the printed values with this code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号