tags:

views:

242

answers:

11

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<malloc.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$
+12  A: 

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

Mark Wilkins
But, i am getting the same address every time.. Why?
shadyabhi
Because it is the same variable every time.
Adam Goode
@Adam: It's not "really" the same variable every time, it's just in the same location every time (in this implementation, and in almost any plausible implementation of C)
Steve Jessop
+1  A: 

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.

Arkaitz Jimenez
+2  A: 

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.

Peter Alexander
+6  A: 

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.

Graham Lee
+2  A: 

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?

Jack
+4  A: 

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.

Todd Gardner
A: 

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.

Tobias Wärre
You mustn't free j in this case since it wasn't dynamically allocated.
Ori Pessach
Well, if the question wasn't edited once in a while to add or remove the call to malloc, then the answer would be a walk in the park.
Tobias Wärre
A: 

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;
}
geocar
+1  A: 

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).

Clifford
A: 

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.

Pasi Savolainen
+5  A: 

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.

Andrew O'Reilly
A nice answer. Now, thats the kind of answer I wanted!!!
shadyabhi
Just in case, if someone needs to know how to get the assembly code.. Use $gcc -S foo.c
shadyabhi
@Andrew - Pls tell a nice source to learn Assembly language. I only have knowledge of LC3. Now, I want to understand assembly codes for lets say Core2Quad.
shadyabhi
shadyabhi
@shadyabhi - Dr Paul Carter's "PC Assembly Language" book is a great introduction to x86 assembly code and be downloaded for free from here http://www.drpaulcarter.com/pcasm/. Randall Hyde has a free pdf appendix to his Writing Great Code Vol 2 book that describes the core x86 instruction set, http://homepage.mac.com/randyhyde/webster.cs.ucr.edu/www.writegreatcode.com/Vol2/wgc2_OA.pdf. You can use this along with gcc -S (or gdb's disassemble command) to explore the assembly code that compilers emit.
Andrew O'Reilly
What about x86_64? Bcos I have 64 bit ubuntu.. How can I understand the output og "gcc -S"?
shadyabhi
I haven't had the time to learn x86_x64 yet so I don't have anything I'd recommend I'm afraid. From what I understand x64 is quite similar to x86 so an investment in learning x86 is not wasted. You can put gcc in x86 mode on a x64 system via the -m32 option. When I do get around to learning x64 I'll probably grab an instruction set summary from somewhere and start walking through the assembly code created by gcc for a variety of usecases.
Andrew O'Reilly