为什么不重新分配收缩数组? [英] Why isn't realloc shrinking the array?

查看:108
本文介绍了为什么不重新分配收缩数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法减小动态创建的数组的大小.这是我的main函数的样子:

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;
}

printf("%d\n", b[8]);行外,其他所有东西都可以正常工作,因为它会打印64,但不会像我期望的那样引起SEGFAULT错误.为什么?

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?

我想我错过了一些简单的事情,因为我已经看到很多与realloc缩小内存有关的SO问题,但是所有人都说这是可能的.

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.

我正在将Ubuntu 14.04和GCC 4.8.2一起使用,并使用-std=c99选项进行编译.

I'm using Ubuntu 14.04 with GCC 4.8.2 and compiling it with -std=c99 option.

推荐答案

b[8]访问未分配的内存,并调用未定义的行为.这就是基本上未定义的行为的含义.结果是不可预测的.它似乎工作正常,但下次可能会崩溃.这里没有其他要考虑的事情-

b[8] in the second printf call accesses memory which is not allocated and invokes undefined behaviour. That's what basically undefined behaviour means. The result is unpredictable. It might seem to be working fine but the next time it may, very well, crash. There are few other things to consider here -

  • malloc可能无法分配内存,因此用assert宏检查其返回值是错误的. assert应该用于调试不可能或错误的代码,例如访问超出其边界的数组.

  • malloc can fail to allocate memory so checking its return value with the assert macro is wrong. assert should be used to debug impossible or wrong code like accessing an array out of its bound.

您不应转换malloc的结果. 我是否强制转换malloc的结果?

You should not cast the result of malloc. Do I cast the result of malloc?

realloc可能无法重新分配像malloc这样的存储块.失败时,它返回NULL并使较旧的块保持不变.这意味着您将无法处理较旧的内存块,从而导致其泄漏.您应在调用realloc之前将指向较旧块的指针存储在变量中.

realloc may fail to reallocate a memory block like malloc. When it fails, it returns NULL and leaves the older block unchanged. This means you would lose handle on the older memory block causing it to leak. You should store the pointer to the older block in a variable before calling realloc.

这篇关于为什么不重新分配收缩数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆