繁体   English   中英

关于使用 realloc 减小 malloc 大小的问题

[英]Question about decreasing malloc size by using realloc

我正在尝试减小 malloc 数组的大小,但是当我为 malloc 重新分配一个较小的大小时,它会抛出 -1073741819 (0xC0000005)。

typedef struct {
    float reproduce_prob;
    int mature;
    int life;
    int age;
    char *direction;
    int X;
    int Y;
} slug;
slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount + 1));
int slugCount = 0;
                        if (slugCheck(theGrid, frogs[i])) {
                            int pos = feedFrog(frogs[i], slugs, slugCount);
                            for (int z = pos; z < slugCount - 1; z++) {
                                slugs[z] = slugs[z + 1];
                            }
                            slugCount--;
                            slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));
                            frogs[i].initHung = 0;
                        }

slugCount 不为零。

最好在sizeof中使用对象而不是类型。 拥有独特且有意义的类型和变量名称以避免此类错误也很好。 我会调用slug slugTypeslug_type

在这一行中,您没有分配足够的空间(假设 slug 结构大于指针),因为 sizeof(slugs) 将指针的大小提供给slug

slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));

您还错误地使用了 realloc,因为 realloc 可能会失败,您将有 memory 泄漏

slug *tmp;
tmp = realloc(slugs, sizeof(*tmp) * (slugCount + 1));
if(tmp)
{
    slugs = tmp;
}
else
{
    /* error handling */
}

作为旁注:不要malloc系列函数的结果。 如果你的代码没有通过编译就意味着你使用C++编译器编译了C语言代码。 这不是一个好主意,因为 C 和 C++ 是不同的语言,即使语法看起来相似。

这段代码如何编译?

slug *slugs = (slug *) malloc(sizeof(slug) * (slugCount + 1));
int slugCount = 0;

编译器应该对你大喊大叫,因为你在定义slugCount之前就使用了它。

如果正在构建此代码,则意味着您已经在封闭的slugCount中定义了 slugCount,并且它的值可能不为零。 这是一个问题。

您应该始终检查malloccallocrealloc的结果。 您确定mallocrealloc调用都没有返回NULL吗?

这一行是可疑的:

slugs = realloc(slugs, sizeof(slugs) * (slugCount + 1));

sizeof(slugs)为您提供指针的大小,而不是slug类型 - 您没有将数组扩展一个元素,而是将其缩小了很多。 您可能想将其更改为

slug *tmp = realloc( slugs, sizeof *slugs * (slugCount + 1) );

您应该始终将realloc的结果分配给一个临时变量。 realloc如果不能满足请求会返回NULL并保留原来的buffer 但是,如果将NULL结果分配回原始指针,您将失去对 memory 的唯一引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM