Dynamically reallocating an array of structures in C

Some of my code will read in an unknown number of lines from a text file, parse that line into a structure (tempSomeStruct), resize SomeStruct_Array, and then add this tempSomeStruct to the newly opened memory location.

However, after a few times through the while loop, my program stops and says

myApplication.exe caused a breakpoint.

I didn't set a breakpoint and didn't do some digging, this LOOKS like a heap corruption breakpoint from my realloc call. I'm new to dynamic hosting, so while I searched and found several possible causes, there are still no bugs fixed.

How do I corrupt the bunch in this situation, and what do I do differently to avoid it?


I have a function like this:

int growArray(SomeStruct **SomeStruct_Array,int currentSize, int numNewElements)
{
    const int totalSize = currentSize + numNewElements;
    SomeStruct *temp = (SomeStruct*)realloc(*SomeStruct_Array,(totalSize * sizeof(SomeStruct)));
    if (temp == NULL)
    {
        printf("Cannot allocate more memory.\n");
        return 0;
    }
    else
    {
        *SomeStruct_Array = temp;
    }

    return totalSize;
}

      

and it gets called elsewhere:

SomeStruct* SomeStruct_Array = (SomeStruct *) calloc(1,sizeof(SomeStruct));
int Error_Array_Size = 0;

if(SomeStruct_Array == NULL)
{
   printf("Cannot allocate initial memory for data\n");
   return;
}

while(fgets(line,sizeof(line), file) != NULL)
{
   parseTextIntoSomeStruct(line, &tempSomeStruct);
   SomeStruct_Array_Size = growArray(&SomeStruct_Array,SomeStruct_Array_Size,1);
   if(SomeStruct_Array_Size > 0)
   {
      SomeStruct_Array[SomeStruct_Array_Size] = tempSomeStruct;
   }
}

      

+3


source to share


1 answer


Your new size of the array SomeStruct_Array_Size

, and you will immediately write to SomeStruct_Array[SomeStruct_Array_Size]

, which is beyond the end of the array! Remember that C arrays are zero-indexed.

Using



SomeStruct_Array[SomeStruct_Array_Size-1] = tempSomeStruct;

      

instead.

+1


source







All Articles