C – continuation

by Vasil Kolev

As a continuation of the previous posting, one explanation, as looks like it’s needed :)

So, again the three fragments:

Fragment 1:

char *pesho="pesho";

Fragment 2:

char *pesho=(char *) malloc (6);
strcpy(pesho,"pesho");

Fragment 3:

char pesho[6]="pesho";

The first fragment writes the string in the .rodata section (before the executable code) and makes the pointer to point there. You can’t write there (except if you’re running DOS or something else with no memory protection), but can be passed around as a pointer.

The second fragment allocates memory in the heap and writes the string there. The pointer can be passed around, the space written to, etc..

The third fragment has two sub-cases: if pesho is a global or a local variable. In the first case the memory is allocated in the .globl section where the global variables are written with their names, so the dynamic linker can decide which is where – this one can be passed around, to be written to, etc.. The second one it’s local to the function, it’s allocated in the stack and the pointer can be passed to functions that are called by this one, but not returned by it (because when you leave the function the memory gets deallocated).

If you want to see for yourself what happens, write those in a program and compile it to assembly code with

gcc -Wall -o pesho.s -S pesho.c

and look at pesho.s, it’s pretty much obvious.

This was also tested on a few unixes (32 and 64bit) and 32bit Visual C++.

Leave a Reply