简体   繁体   English

重新分配结构数组会出错 - 下一个大小无效

[英]reallocing array of structs gives error - invalid next size

I am writting a program that creates an array of structs (dynamically allocated).我正在编写一个程序来创建一个结构数组(动态分配)。 The code works until the array needs to be enlarged and even after checking everything I could think of and trying all sorts of tips from SO, it doesn't seem to work.该代码在需要扩大数组之前一直有效,即使在检查了我能想到的所有内容并尝试了 SO 的各种提示之后,它似乎也不起作用。 None of this , that , those or these solved it. 那个那些这些都没有解决它。

Here is the problematic part of code:这是代码有问题的部分:

    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;
}

Notes: 1) I know x = realloc (x, ...) is a BAD practise, but this will be running in a school testing environment with no error handling options, so there is no point in making a tmp_ptr.注意:1)我知道x = realloc (x, ...)是一种不好的做法,但这将在没有错误处理选项的学校测试环境中运行,因此制作 tmp_ptr 毫无意义。 2) I also know that casting a malloc and realloc is not the cleanest approach, but again, it is a rigid school testing environment for C course and it compiles with g++ . 2)我也知道转换 malloc 和 realloc 不是最干净的方法,但同样,它是 C 课程的严格学校测试环境,并且它使用g++编译。 This way the compiler doesn't give me warnings.这样编译器就不会给我警告。

EDIT: The code compiles, runs without issue when reallocation isn't needed.编辑:代码编译,在不需要重新分配时运行没有问题。 Once the input data exceeds memory allocated by malloc, this shows:一旦输入数据超过 malloc 分配的内存,就会显示:

realloc(): invalid next size
Aborted (core dumped)

Your actual allocation is for array of pointers, not array of structs.您的实际分配用于指针数组,而不是结构数组。 If you want to make room for say n distance objects, you should call malloc( sizeof(distance) * n) while all I can see is malloc( sizeof(distance*) ...) .如果你想为 n 个distance对象腾出空间,你应该调用malloc( sizeof(distance) * n)而我只能看到malloc( sizeof(distance*) ...) As your struct is probably greater in size than a pointer, there is not enough memory allocated.由于您的结构的大小可能大于指针,因此没有分配足够的内存。

Side note: realloc in double loop is bad idea.旁注:在双循环中重新分配是个坏主意。 Try to do the math first, and use realloc only, if truly needed.尝试先进行数学计算,并仅在确实需要时才使用 realloc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM