【问题标题】:Ensure the allocation of memory is of the right size [duplicate]确保内存分配的大小正确[重复]
【发布时间】:2021-05-06 18:17:22
【问题描述】:

我好像有一个看不懂的问题,实验室助理说“你的内存分配不会分配正确的大小,你需要使用类型本身的大小而不是变量的大小。”。

我曾尝试使用 sizeof (struct object) 这样的 printf("%d", sizeof(struct object)); 来查看大小并返回 36。在分配中,大小与struct object 相同,所以我有点不明白为什么它会分配错误的大小。当我运行它时,分配似乎对我来说是正确的,并且在调试器中它没有显示任何错误,所以如果有人可以看看,我将不胜感激。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NameLength 20
#define UnitLenght 10

struct object
{
    char name[NameLength];
    float amount;
    char unit[UnitLenght];
};
struct inventory
{
    struct object *add;
    int nrOfobject;
};

void allocateMemory(struct inventory *allItem);

int main(void)
{
    struct inventory shopping = {NULL, 0};
    allocateMemory(&shopping);

return 0;
}

void allocateMemory(struct inventory *allItem)
{
    struct object *tempurary;
    if (allItem->nrOfobject == 0)
        tempurary = (struct object *)calloc(1, sizeof(*tempurary));
    else
        tempurary = (struct object *)realloc(allItem->add, sizeof(*tempurary)*(allItem->nrOfobject +1));
    allItem->add = tempurary;
}

【问题讨论】:

  • tempurary = (struct object *)calloc(1, sizeof(*tempurary)); 可以,但可以减少到 tempurary = calloc(1, sizeof *tempurary); 和 "tempurary" --> "temporary"
  • allocateMemory() 的潜在问题 --> 我希望在某个地方出现llItem-&gt;nrOfobject++;
  • 代码看起来有效,除了 chux 关于增加 nrOfobject 的观察。我不认为有一个很好的理由让 0 特殊情况:allItem-&gt;add = realloc(allItem-&gt;add, sizeof(object) * ++allItem-&gt;nrOfObject); 似乎可以做所有事情。 (如果你将 NULL 传递给 realloc,它与 malloc 相同)。
  • 当然sizeof(struct object)sizeof(*tempurary)是一样的。推荐使用sizeof(*tempurary) 背后的想法是,变量名称通常会出现在分配附近,如tempurary = calloc(1, sizeof(*tempurary));,而指定其类型的声明(如struct object *tempurary;)可能在更大的程序中的其他位置。如果您不小心指定了错误的变量(例如,来自复制和粘贴),与不小心指定了错误的类型相比,这个错误更容易被发现。
  • @Jacob 不,保留你所拥有的。如果类型名称发生更改,则不太容易出错。

标签: c memory struct dynamic-memory-allocation


【解决方案1】:
void allocateMemory(struct inventory *allItem)
{
    struct object *tempurary;
    if (allItem->nrOfobject == 0)
        tempurary = (struct object *)calloc(1, sizeof(*tempurary));
    else
        tempurary = (struct object *)realloc(allItem->add, sizeof(*tempurary)*(allItem->nrOfobject +1));
    allItem->add = tempurary;
}

大小看起来是正确的,尽管我会删除不必要的演员表,并清除第一个元素(因为我们不会将后续元素归零)。另外,在覆盖指针之前检查realloc()的结果(否则我们会留下内存泄漏):

int allocateMemory(struct inventory *allItem)
{
    struct object *temporary;
    if (allItem->nrOfobject == 0) {
        temporary = malloc(sizeof *temporary);
    } else {
        temporary = realloc(allItem->add, (sizeof *temporary)*(allItem->nrOfobject + 1));
    }
    if (!temporary) {
        return 0;
    }
    allItem->add = temporary;
    return ++allItem->nrOfobject;
}

【讨论】:

  • 可能是allItem-&gt;add[allItem-&gt;nrOfobject] = (struct object){0};return之前的类似名称。
  • 是的,如果这是Code Review,我会正确处理不变量。但我认为,我已经超出了 SO 的范围。
猜你喜欢
  • 1970-01-01
  • 2010-09-27
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多