Search code examples
cmemory-managementmemory-leaksgdbfree

C dynamic memory problems with malloc() and free()


I dynamically allocated 2 different arrays with 1 million cells each. One array holds integers and one array holds pointers to strings of fixed length. When I run my program using gdb I'm getting the error: free(): invalid next size (fast). I must be freeing memory in an illegal way, but I can't figure out how. I've posted a brief snippet of my code below where I am using malloc and free. Can you tell me what I'm doing incorrectly? Thank you.


Solution

  • Except for being a bit strange, (see iharob's comment,) the code you are showing us appears correct.

    The error is most probably not in the code you are showing us.

    What is probably happening is that somewhere else you are filling-in those "words" of yours with characters, and you are storing more than 20 characters starting at the address of wc->allWords[i]. So, you are writing past the end of a block of memory, and over the header of the next block of memory.

    Then, later, the address of the block you are trying to free is correct, but you have damaged the header of the block, so free() fails.