我无法减小动态创建的数组的大小。这是我的main
函数的样子:
int main(void) {
// Intialize big array
int * a = (int *)malloc(10*sizeof(int));
assert(a);
// Fill it with squares
for (int i = 0; i < 10; ++i)
a[i] = i*i;
// Expected to print 64
printf("%d\n", a[8]);
// Shrink the big array
int * b = (int *)realloc(a, 5*sizeof(int));
assert(b);
// Expected to cause SEGFAULT
printf("%d\n", b[8]);
return 0;
}
一切正常,除了printf("%d\n", b[8]);
行,因为它打印64
,但没有像我预期的那样导致 SEGFAULT 错误。为什么?
我想我错过了一些简单的东西,因为我已经看到了很多与缩小内存有关的 SO 问题realloc
,但他们都说这是可能的。
我正在使用带有 GCC 4.8.2 的 Ubuntu 14.04 并使用-std=c99
选项编译它。