anon
anon

Reputation: 49

munmap_chunk(): invalid pointer, when to use free()

I'm curious as to why free(myWord->w) would be an invalid pointer? I allocate memory to it, so shouldn't I free it as well? or does freeing a struct also free all of its fields?

New to C so any insight on the world of pointers is much appreciated!

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct word {
    char *w;
} WORD;

void setWord(char **f);

int main() {

    WORD *myWord = malloc(sizeof(WORD));
    myWord->w = malloc(6);
    strcpy(myWord->w, "hello"); // set to "hello"
    setWord(&(myWord->w));      // set to "bagel"


    free(myWord->w); /* munmap_chunk(): invalid pointer. Aborted (core dumped) */
    free(myWord);

    return 0;

}

void setWord(char **F) {
    *F = "bagel";
}

Upvotes: 0

Views: 983

Answers (1)

4386427
4386427

Reputation: 44274

*F = "bagel"; is not how you assign a string. Instead the code overwrite the value of the pointer myWord->w so when you call free, it's no longer the correct pointer value.

To see that the pointer change, try this:

printf("%p\n", (void*)myWord->w);
setWord(&(myWord->w));      // set to "bagel"
printf("%p\n", (void*)myWord->w);

Consequently, the free call will fail as the pointer-value isn't the one you got from the malloc.

So instead of *F = "bagel"; use

strcpy(*F, "bagel");   // NOT: *F = "bagel"

Further you don't need to pass the address of w. Simply do:

void setWord(char *F) {
    strcpy(F, "bagel");
}

and call it like:

setWord(myWord->w);

And...

I allocate memory to it, so shouldn't I free it as well? or does freeing a struct also free all of its fields?

Yes, you must free it.

No, free of a struct does not free members automatically. You must do that.

Upvotes: 1

Related Questions