【问题标题】:reallocing array of structs gives error - invalid next size重新分配结构数组会产生错误 - 下一个大小无效
【发布时间】:2019-12-02 22:02:19
【问题描述】:

我正在编写一个程序来创建一个结构数组(动态分配)。该代码一直有效,直到需要扩大数组,即使在检查了我能想到的所有内容并尝试了 SO 的各种提示之后,它似乎也不起作用。 thisthatthosethese 都没有解决它。

下面是代码有问题的部分:

    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,否则我们无法提供真正的帮助。

标签: c struct realloc


【解决方案1】:

您的实际分配是针对指针数组,而不是结构数组。如果你想为 n 个distance 对象腾出空间,你应该调用malloc( sizeof(distance) * n),而我只能看到malloc( sizeof(distance*) ...)。由于您的结构可能比指针大,因此分配的内存不足。

旁注:双循环中的 realloc 是个坏主意。尝试先进行数学运算,仅在确实需要时才使用 realloc。

【讨论】:

  • 谢谢,我也会尝试使用 malloc。尽管考虑了一下,尽管 malloc 数学可能有误,但它不应该给出错误(对少数条目工作正常)。由于//...stuff here 部分存在双循环(第一个循环中没有真正发生,只是计算两个不同位置的索引)。但我会在早上仔细考虑一下。感谢您指出。
猜你喜欢
  • 2014-01-23
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
相关资源
最近更新 更多