Why isn't realloc shrinking the array?

﹥>﹥吖頭↗ 提交于 2019-12-04 06:18:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!