Why is my memory layout different?

The following code snippet:

void (*foo)();
char X[1];
char Y[10];

could intuitively give me one possible alignment:

|  Y[10]  |
|---------|
|  X[1]   |
|---------|
|  foo    |
|---------|

I studied this by creating an ASM file using:

gcc -S -o stack stack.c

Then I realized that the order in which these variables are pressed is different. So, if I accidentally did X[1], I expected to refer to Y[0], but in the actual layout, writing something in X[1]overwrites the first byte of the memory cell allocated for foo. Is reorganization a compiler optimization step or can someone tell me why this is happening?

+3
source share
6 answers

Why do you say "need"?

, - , , .

, "".


, ( , !) , struct #pragma s.

+4

, . , , , . , , , , .

, , , - , . , . , , , , . , , , .

-, . :

push A
push B

A , B, B ( A). C:

int stk[BIG];
int stk_top = BIG;

 void stk_push(int x) {
     stk_top--;
     stk[stk_top] = x;
 }

, stk_top , .

- , , . , , , . , . , , , . , . , . , , , .

+2

: char , .

, "" , . , 32- int 32- . , "" , .

, , .

+1
|   var   | address |
|---------|---------|
|  Y[10]  |  x      |
|---------|---------|
|  X[1]   |  x + 10 |
|---------|---------|
|  foo    |  x + 11 |
|---------|---------|

, , ( ), , , . , X[1] = *(x + 10 + 1) = foo

+1

, .

+1

, ? 4- . ?

char x[11];
char *y = &x[1];
+1

Source: https://habr.com/ru/post/1770566/


All Articles