Home > other >  Why do I get the error: "double free or corruption(out) core dumped Aborted core dumped",
Why do I get the error: "double free or corruption(out) core dumped Aborted core dumped",

Time:05-29

I have used a malloc 2-D array and this it:

charArray = (char **)malloc(rows * sizeof(char *));
for (i = 0; i < columns; i  )
    charArray[i] = (char *)malloc(columns * sizeof(char *));

And when I try to free the memory, it says: "double free or corruption(out). Aborted (core dumped). This is how i free it:

for (i = 0; i < rows; i  ) {
    free(charArray[i]);
    charArray[i] = NULL;
}

free(charArray);
charArray = NULL;

Why do I get this error and how can I fix it? This is the valgrind report:

enter image description here

CodePudding user response:

From the code you posted it is hard too see.

Make your life easier and use array pointers.

char (*charArray)[columns] = malloc(rows * sizeof(*charArray));

Only one allocation and free is needed. Fewer levels of indirection - faster code.

CodePudding user response:

Your code fragment is terse to say the least, but there is a problem in the allocation loop: for (i = 0; i < columns; i ) should iterate on rows, not columns and allocate columns characters, not pointers.

If rows and columns differ, you have undefined behavior:

  • either columns > rows and the allocation code writes pointers beyond the end of the allocated block for charArray
  • or rows > columns and you attempt to free pointers that were not allocated and are probably invalid.

To avoid such mistakes, it is recommended to use sizeof with type of the destination element:

    char **charArray = calloc(rows, sizeof(*charArray));
    for (i = 0; i < rows; i  )
        charArray[i] = calloc(columns, sizeof(*charArray[i]));

It would also be simpler to allocate a flat 2D array of char instead of an indirect array:

    char (*charArray)[columns] = calloc(rows, sizeof(*charArray));

This array is also simpler to free:

    free(charArray);
  • Related