Where are anonymous objects stored?

107 Views Asked by At

I expected them to be stored in the text segment, but a short investigations revealed they are not (I used clang compiler). So where then are they stored? The pointers to anonymous objects are defined globally (outside any scope) like this:

int *garr = (int[]){1, 2, 3, 4, 5};
void *grec = &(struct {float a; char b;}){0, 1};

I defined a pointer to a string literal and some constant variables globally:

char *gstr = "Global string";
const short global_const = 5;
static const unsigned static_global_const = 10;

Then I defined some variables for the data segment, also globally:

int data_x = 1;
char data_y = 2;
static float data_z = 3;

Then I checked the addresses of all of them and the content of the gstr pointer to get an idea where the text and the data segments are. The result was like this (lstr is a pointer to another string literal, but defined inside the main scope):

gstr == 0x4009a8
lstr == 0x400a18
&global_const == 0x400bb4
&static_global_const == 0x400bbc

&data_x == 0x601070
&data_y == 0x601074
Static: &data_z == 0x601078

Here what I see is that the first 4 addresses come from the text segment while the last 3 are from the data segment. I had expected anonymous objects to be near the first 4 addresses, but I saw this:

garr == 0x601040
grec == 0x601060

To me looks like they got stored into the data segment even though these objects are read-only literals. Why?

1

There are 1 best solutions below

1
On BEST ANSWER

Compilers commonly put string literals in a read-only section because they are read-only. Similarly, initialized non-read-only data is put in a modifiable data section because that is what it is for.

A compound literal is not read-only unless it is defined with a const-qualified type, so a compiler is likely to put a non-const-qualified compound literal in a modifiable section.

(Of course, the C standard allows C implementations to arrange memory as they like, so a compiler is not obligated to use the same section for compound literals that it uses for other data.)