top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Memory allocation of variables in C?

+3 votes
386 views
main {
 int a;
 a = 10;
}

Here, when the memory will be allocated.
Compile/Run time? why ?

posted Mar 20, 2014 by sivanraj

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Many times, the answer really depends on compiler - due to various optimizations.

So, best way is to compile the code, run it under gdb and inspect the assembly code. Here's what I got:

(gdb) b main
(gdb) run
Starting program: /home/Mehul/a.exe
[New thread 4484.0x150c]

Breakpoint 1, 0x00401056 in main ()
(gdb) disassemble
Dump of assembler code for function main:
0x00401050 <main+0>: push %ebp
0x00401051 <main+1>: mov %esp,%ebp
0x00401053 <main+3>: sub $0x8,%esp
0x00401056 <main+6>: and $0xfffffff0,%esp
0x00401059 <main+9>: mov $0x0,%eax
0x0040105e <main+14>: add $0xf,%eax
0x00401061 <main+17>: add $0xf,%eax
0x00401064 <main+20>: shr $0x4,%eax
0x00401067 <main+23>: shl $0x4,%eax
0x0040106a <main+26>: mov %eax,-0x8(%ebp)
0x0040106d <main+29>: mov -0x8(%ebp),%eax
0x00401070 <main+32>: call 0x401084 <_alloca>
0x00401075 <main+37>: call 0x401114 <__main>
0x0040107a <main+42>: movl $0xa,-0x4(%ebp)
0x00401081 <main+49>: leave
0x00401082 <main+50>: ret

So, as you can see, after calling function main, 0xa is put on the stack. Memory is allocated on the stack.

But, let's tweak the source code:

main() {
int a, b;
a=10;
b = a;
}

One would assume that stack would have two integers - however, if you compile with "gcc -o3 tmp.c".

After that, if you see the assembly code, it's exactly same as above for stack allocation.

Fun.

answer Mar 21, 2014 by Mehul Bhatt
Similar Questions
+4 votes
printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);
[Error] invalid operands to binary + (have 'struct name' and 'int')

where ptr is a pointer to the structure and allocated dynamic memory using malloc. Any suggestion would be helpful.

Thanks in advance.

+4 votes

Is there any alternate function is available?

+3 votes

Please help me to print all permutations of a string in C?

+1 vote

Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.

...