为什么在此字符串中增加一个字节会使它在堆栈中又占用16个字节?

时间:2019-05-03 19:39:33

标签: c gcc memory

我具有以下功能:

void f(){
    char a[]="THIS IS A STR 1";
    char b[]="THIS IS A STR 2";
    char c[]="THIS IS A STR 3";
    char d[]="THIS IS A STR 4";
}

这四个字符串在堆栈中的分配方式如下:

08 00 00 00 04 00 00 00 10 00 00 00 10 00 00 00 ................
40 c0 17 2a fc 7f 00 00 07 49 2f fa 6d 55 00 00 @..*.....I/.mU..
54 48 49 53 20 49 53 20 41 20 53 54 52 20 31 00 THIS IS A STR 1.
54 48 49 53 20 49 53 20 41 20 53 54 52 20 32 00 THIS IS A STR 2.
54 48 49 53 20 49 53 20 41 20 53 54 52 20 33 00 THIS IS A STR 3.
54 48 49 53 20 49 53 20 41 20 53 54 52 20 34 00 THIS IS A STR 4.
a0 99 a8 0f 27 7f 00 00 00 32 a9 91 1c f3 d3 49 ....'....2.....I
60 c0 17 2a fc 7f 00 00 37 49 2f fa 6d 55 00 00 `..*....7I/.mU..

当我在每个字符串中添加一个字符以使其更长时,如下所示:

void f(){
    char a[]="THIS IS A STR 1 ";
    char b[]="THIS IS A STR 2 ";
    char c[]="THIS IS A STR 3 ";
    char d[]="THIS IS A STR 4 ";
}

像这样在堆栈上分配字符串:

08 00 00 00 04 00 00 00 10 00 00 00 10 00 00 00 ................
50 0e c3 65 fe 7f 00 00 17 e9 0b 97 bd 55 00 00 P..e.........U..
54 48 49 53 20 49 53 20 41 20 53 54 52 20 31 20 THIS IS A STR 1
00 32 c6 65 fe 7f 00 00 10 17 62 c0 62 7f 00 00 .2.e......b.b...
54 48 49 53 20 49 53 20 41 20 53 54 52 20 32 20 THIS IS A STR 2
00 00 00 00 00 00 00 00 47 65 6e 75 00 00 00 00 ........Genu....
54 48 49 53 20 49 53 20 41 20 53 54 52 20 33 20 THIS IS A STR 3
00 0e c3 65 fe 7f 00 00 ff b5 f0 00 00 00 00 00 ...e............
54 48 49 53 20 49 53 20 41 20 53 54 52 20 34 20 THIS IS A STR 4
00 89 40 c0 62 7f 00 00 00 6c 59 06 5f 7c 70 d6 ..@.b....lY._|p.
70 0e c3 65 fe 7f 00 00 47 e9 0b 97 bd 55 00 00 p..e....G....U..

我听说内存只能在4个字节的边界上分配,但无法在任何地方提供该内存,即使是这种情况,所使用的额外内存是16个字节,而不是4个字节。

这是在Linux上使用gcc编译的。

谢谢!

编辑:

我认为这个问题已经得到解答here.

0 个答案:

没有答案