【发布时间】:2019-12-02 22:02:19
【问题描述】:
我正在编写一个程序来创建一个结构数组(动态分配)。该代码一直有效,直到需要扩大数组,即使在检查了我能想到的所有内容并尝试了 SO 的各种提示之后,它似乎也不起作用。 this、that、those 或 these 都没有解决它。
下面是代码有问题的部分:
struct distance {
...;
} *dist;
int main ( void )
{
unsigned int len_max = 128;
unsigned int current_size = len_max * sizeof(distance);
unsigned int distN = 0; //counter
dist = (distance*) malloc(sizeof(distance*) * len_max);
for(unsigned int k = 0; k < i; k++)
{
for(unsigned int l = k+1; l < i; l++)
{
if(distN*sizeof(distance) >= current_size) // bug here?
{
current_size = 2*(distN) * sizeof(distance*);
dist = (distance*)realloc(dist, current_size);
}
//... do stuff
distN++;
}
}
return 0;
}
注意事项:
1) 我知道x = realloc (x, ...) 是一种不好的做法,但这将在没有错误处理选项的学校测试环境中运行,因此制作 tmp_ptr 没有意义。
2) 我也知道强制转换 malloc 和 realloc 不是最干净的方法,但同样,它是 C 课程的严格学校测试环境,它使用g++ 编译。这样编译器不会给我警告。
编辑:代码编译,在不需要重新分配时运行没有问题。一旦输入数据超过了 malloc 分配的内存,这表明:
realloc(): invalid next size
Aborted (core dumped)
【问题讨论】:
-
g++是一个 c++ 编译器。使用gcc编译c。 “似乎不起作用”的描述非常模糊。 “似乎不起作用”是什么意思?您如何检测到某些东西“不起作用”?它编译吗?它运行吗?它会让你的电脑着火吗?请不要描述它不起作用,而是显示会发生什么、何时发生以及您希望发生什么。请注意如何将sizeof(distance*)与sizeof(distance)混合使用 - 可能不存储大小,而是将 count 元素存储在数组中,然后将其乘以 re-/m-alloc 中的大小 -
distance*不是 C,必须是struct distance*。 -
invalid next size。 realloc 本身并没有给出那个错误。最可能的原因是您的代码中存在内存损坏。它可能在您的代码中的任何位置,并且可能不在您显示的部分中。因此,除非您提供 minimal reproducible example,否则我们无法提供真正的帮助。