Zera42
Zera42

Reputation: 2692

using free() with a struct pointer makes program crash

Error:

*** Error in `./main': free(): invalid next size (fast): 0x080e1008 ***
Aborted

This is my program, and it's crashing when I try to deallocate a struct.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
//struct words contains a word as well as a boolean
//to check if it was used yet or not.
struct words
{
    char * word;
    int bool;
};
//the main function in which everything happens.
//the controller, if you will.
int main()
{
    struct words * word_library = malloc(9);
    struct timeval start, end;
    free(word_library);
    return 0;
}

So this is the code making my program crash:

free(word_library);

What is causing it to crash? And how can prevent this in the future? I know that every use of malloc() requires the free() after to deallocate it. But when I don't use free() it ends just fine, but I'm sure there's a memory leak.

Upvotes: 0

Views: 1179

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

This:

struct words * word_library = malloc(9);

doesn't allocate space for an array of struct words of size 9. Instead, it allocates 9 bytes. You need

struct words * word_library = malloc(sizeof(struct words)*9);

to allocate an array of size 9.

You also don't need to allocate and deallocate memory for word in the struct if you are going to make them point to string literals.

Upvotes: 4

Related Questions