【问题标题】:C: Error using malloc and realloc on array of structsC:在结构数组上使用 malloc 和 realloc 时出错
【发布时间】:2021-03-04 02:25:17
【问题描述】:

我正在尝试为图形上的算法动态分配内存。这是我的代码分解为问题:

typedef struct
{
    int id;
    int color;
} node_t;

unsigned int max_n = 2;
node_t* node_malloc = malloc(sizeof(node_t) * max_n);
node_t* nodes = node_malloc;

if(atoi(left_node) > max_n)
{
    max_n = (size_t) atoi(left_node);
    nodes = realloc(nodes, sizeof(node_t) * max_n);
}

对于 max_n

free(node_malloc);

在 realloc 发生后调用 free(node_malloc) 时,它会抛出“free(): invalid next size (fast)”

感谢您的回答!

【问题讨论】:

  • “不起作用”是什么意思?
  • 是的,抱歉,补充说。当它没有重新分配时我确实工作,但当它重新分配时我不工作。
  • 这也取决于你如何写入数组。在atoi() 和所有这些中看不到任何好处。并考虑到你不想打包struct,所以会有很多差距,如果在上面做一些定制的事情肯定会变得很糟糕。

标签: c struct malloc free realloc


【解决方案1】:

发生的情况是realloc 调用后,nodes_malloc 中的指针值不再有效。如果realloc无法原地扩展当前缓冲区,它会为一个new缓冲区分配空间,将旧缓冲区的内容复制到其中,然后释放旧缓冲区,这显然是发生了什么当您扩展超过 9 个元素时。

nodes 用作realloc 调用的临时目标 - 如果不是NULL(意味着realloc 成功),则将其分配回nodes_malloc

nodes = realloc( nodes_malloc, sizeof *nodes * max_n );
if ( nodes )
{
  nodes_malloc = nodes;
}
else
{
  // realloc failed
}

【讨论】:

  • 是的,并将其放入自己的函数中。您可能需要多次使用它。 ;)
  • 谢谢。我按照你说的做了,现在 free(node_malloc) 工作正常。现在:当我调用 realloc(nodes_malloc, sizeof *nodes * 29);我得到“免费():无效大小”!
【解决方案2】:

你有这个:

node_t* node_malloc = malloc(sizeof(node_t) * max_n);
node_t* nodes = node_malloc;

之后,指针node_mallocnodes 都指向同一个内存。

但在第一次致电realloc 之后,就不再有保证了。事实上,几乎确定nodes 将指向其他地方,而node_malloc 指针将无效。

尝试free(node_malloc) 将导致未定义的行为


在相关问题上,您永远不应该将指针分配回您传递给realloc 的指针。如果realloc 失败,它将返回NULL,但旧的内存分配将保持有效。如果您重新分配回相同的指针,则会丢失原始内存并发生内存泄漏。始终使用临时变量,并检查是否失败 (NULL)。

【讨论】:

  • OP 应该将free(node_malloc) 替换为free(nodes)
猜你喜欢
  • 2012-09-19
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多