5

here is a simple code that I executed

int a;
int main()
{
    return 0;
}

Then after compiling with gcc I did

size a.out

I got some output in bss and data section...Then I changed my code to this

int a;
int main()
{
    char *p = "hello";
    return 0;
}

Again when I saw the output by size a.out after compiling , size of data section remained same..But we know that string hello will be allocated memory in read only initialized part..Then why size of data section remained same?

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
user1205088
  • 229
  • 2
  • 11

5 Answers5

5
#include <stdio.h>

int main()
{
return 0;
}

It gives

   text    data     bss     dec     hex filename
    960     248       8    1216     4c0 a.out

when you do

int a;
int main()
{
    char *p = "hello";
    return 0;
}

it gives

   text    data     bss     dec     hex filename
    982     248       8    1238     4d6 a.out

at that time hello is stored in .rodata and the location of that address is stored in char pointer p but here p is stored on stack

and size doesnt shows stack. And i am not sure but .rodata is here calculated in text or dec.


when you write

int a;
char *p = "hello";
int main()
{
    return 0;
} 

it gives

   text    data     bss     dec     hex filename
    966     252       8    1226     4ca a.out

now here again "hello" is stored in .rodata but char pointer takes 4 byte and stored in data so data is increment by 4

For more info http://codingfreak.blogspot.in/2012/03/memory-layout-of-c-program-part-2.html

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
2

Actually, that's an implementation detail. The compiler works by an as-is principle. Meaning that as long as the behavior of the program is the same, it's free to exclude any piece of code it wants. In this case, it can skip char* p = "hello" altogether.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

The string "hello" is allocated in the section .rodata

Serge
  • 6,088
  • 17
  • 27
  • @user1205088 just do "grep hello" on your binary file and see if it is thrown away by compiler or not :) – Serge Sep 27 '12 at 07:58
1

Even if the total size doesn't changed, it doesn't mean that the code didn't.

I tested your example. The string "hello" is a constant data, thus it is stored in the readonly .rodata section. You can see this particular section using objdump, for example:
objdump -s -j .rodata <yourbinary>

With gcc 4.6.1 without any options, I got for your second code:

Contents of section .rodata:
 4005b8 01000200 68656c6c 6f00               ....hello.
Michael Mera
  • 108
  • 7
0

Since you don't use that char * in your code, the compiler optimized it away.

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130