Search code examples
cstructrealloc

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. 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. 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++. 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:

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

Solution

  • 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*) ...). 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.