问题
I have trouble reducing the size of dynamically created array. Here's what my main function looks like:
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;
}
Everything works fine except for printf("%d\n", b[8]); line, as it prints 64, but not causing SEGFAULT error as I expected it to. Why?
I think I missing something simple, because I've seen lots of SO questions related to shrinking the memory with realloc, but all of them say that it's possible.
I'm using Ubuntu 14.04 with GCC 4.8.2 and compiling it with -std=c99 option.
来源:https://stackoverflow.com/questions/23647168/why-isnt-realloc-shrinking-the-array