TheEyesHaveIt TheEyesHaveIt - 1 month ago 4
C Question

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.

My struct:

#define H_SIZE 1000000
struct wc {
int tableSize;
int* table;
char** allWords;

This is how I am allocating the memory:

struct wc* wc;

wc = (struct wc *)malloc(sizeof(struct wc));
wc -> tableSize = H_SIZE;

//malloc array of 1 million integers
wc ->table = (int*)malloc(sizeof(int) * H_SIZE);

//malloc array of 1 million char pointers
wc -> allWords = malloc(sizeof(char*) * H_SIZE);

//malloc 20 character space for each char pointer
int i;
for(i = 0; i < H_SIZE; i++){
wc -> allWords[i] = malloc(20 * sizeof(char));


My destroy function:

wc_destroy(struct wc *wc)

//free each pointer's string in the pointer array
int i;
for(i = 0; i < H_SIZE; i++){
free(wc -> allWords[i]);
//free the array itself
free(wc -> allWords);

//free the integer array
free(wc -> table);

//free the struct


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.