如下的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *a, *b;
int i;
a = (char*) calloc(20, sizeof(char));
b = (char*) calloc(20, sizeof(char));
strcpy(a, "Graduate School of Information Science and Technology");
for(i = 0; i < 20; i++)
printf("b[%d] = %c\n", i, b[i]);
return 0;
}
已知:
b[11] = T
那么,b[12]、b[13]的值是多少?
在linux上创建一个文件t.c,输入代码,然后编译、运行:
[ggg@localhost ~]$ cd Desktop
[ggg@localhost Desktop]$ ls
gnome-terminal.desktop t.c t.c~
[ggg@localhost Desktop]$ gcc -o t t.c
[ggg@localhost Desktop]$ ./t
b[0] = c
b[1] = i
b[2] = e
b[3] = n
b[4] = c
b[5] = e
b[6] =
b[7] = a
b[8] = n
b[9] = d
b[10] =
b[11] = T
b[12] = e
b[13] = c
b[14] = h
b[15] = n
b[16] = o
b[17] = l
b[18] = o
b[19] = g
[ggg@localhost Desktop]$
论坛会员qldsrx的解释是:
其实是和内存分配是否连续有关,如果两次申请的内存是连续内存空间,那么20字节再加上后面申请内存的头部字节(预估是12字节),这样下面一个申请的20字节正好偏移了32字节。
这个时候如果在return之前添加 free(b); 立刻程序崩溃,
因为b这个对象释放时要查找b申请的大小,信息记录在其内存的前面(预估是12个字节),但被改写了。
另外,用visual c++ 6.0尝试了一下,发现数组b中没有任何值,这说明在内存分配上确实和linux平台下的C编译器有很大的差别。