Search code examples
cpointersstructdynamic-memory-allocationdouble-pointer

Double pointer memory allocation to a struct in C


Can't find what is wrong with this code, it works as expected when inputting exactly 4 values, but on the fifth call (before it even asks for scanf) it always gives me this error: * glibc detected ./a2: double free or corruption (fasttop): 0x0916e018 **

Here's some code of my program:

typedef struct {
  int i;
  char str[25];
} typeX;

int main(){
  int dSize = 0;
  int *dSizePtr = &dSize;
  dPointer = (typeX **)malloc(sizeof(typeX *)); // makes an array of pointers
  int i;
  for (i = 0; i < 100; i++)
    makeElement(dPointer, dSizePtr); // Puts values into those pointers
  free(dPointer);
  return 0;
}

void makeElement(dPointer **, int *dSizePtr){
  dPointer = (typeX **)realloc(dPointer, sizeof(typeX *)*(*dSizePtr+1)); // grow the array by one
  if (typeX == NULL)
    return; // some kind of quit statement, just return for now

  dPointer[*dSizePtr] = (typeX *)malloc(sizeof(typeX)); // make a new pointer in the array
  scanf("%s", dPointer[*dSizePtr]->str); // input the values of the struct (have to use scanf)
  char input[20]; 
  scanf("%s", input);
  dPointer[*dSizePtr]->int = atoi(input);

  ++(*dSizePtr);
}

I know I don't have to make a dSizePtr and I can just pass in &dSize, but the way my program is currently set up (this isn't exactly the same, just compressed for readability), that's the way I have to pass it.

I honestly have no idea why this error is coming up. Been looking at my code for hours and reading online and haven't found a solution. Any help will be greatly appreciated!


Solution

  • The problem is that your function makeElement get the value of dPointer, not its reference. When you realloc the data, the originally allocated chunk is freed. But the dPointer outside of the makeElement scope is not changed;

    The runtime error is delayed as the actual memory allocation is performed in quantities bigger than sizeof(typeX*)