重新分配结构数组会产生错误 - 下一个大小无效
reallocing array of structs gives error - invalid next size
我正在编写一个创建结构数组(动态分配)的程序。该代码一直有效,直到需要扩大数组,即使在检查了我能想到的所有内容并尝试了 SO 的各种提示之后,它似乎也不起作用。 , that, or 的 None 已解决。
这是代码中有问题的部分:
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)
您实际分配的是指针数组,而不是结构数组。如果你想为 n distance
个对象腾出空间,你应该调用 malloc( sizeof(distance) * n)
而我只能看到 malloc( sizeof(distance*) ...)
。由于您的结构的大小可能比指针大,因此分配的内存不足。
旁注:双循环中的 realloc 不是个好主意。尝试先计算一下,如果确实需要,只使用 realloc。
我正在编写一个创建结构数组(动态分配)的程序。该代码一直有效,直到需要扩大数组,即使在检查了我能想到的所有内容并尝试了 SO 的各种提示之后,它似乎也不起作用。
这是代码中有问题的部分:
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)
您实际分配的是指针数组,而不是结构数组。如果你想为 n distance
个对象腾出空间,你应该调用 malloc( sizeof(distance) * n)
而我只能看到 malloc( sizeof(distance*) ...)
。由于您的结构的大小可能比指针大,因此分配的内存不足。
旁注:双循环中的 realloc 不是个好主意。尝试先计算一下,如果确实需要,只使用 realloc。