Bato-Bair Tsyrenov
Bato-Bair Tsyrenov

Reputation: 1194

Free char*, when passed as a void in C

I have this function

void clean_strs(void *p){
    if (!p){
        printf("Clean str ptr that is NULL !!\n");
        fflush(stdout);
        return;
    }
    char *a = (char*)p;
    free(a);
    a = NULL;
}

And passing in a pointer like this:

char *a = malloc(4*sizeof(char));
// check if memory was allocated
if(a) {
    a = "asd\0";
    clean_strs(a);
    a = NULL;
    if(a) {
        getchar();
    }
}

Results in signal SIGABORT. Can someone please explain why casting and freeing pointer that was dynamically allocated is an error?

Upvotes: 0

Views: 753

Answers (1)

David Schwartz
David Schwartz

Reputation: 182789

You didn't free a pointer that was dynamically allocated. You freed a pointer to a constant:

a = "asd\0";

You just replaced the value you got from malloc with a pointer to a string constant. You can't free any pointer but one you got from malloc.

You probably wanted:

strcpy (a, "asd");

Upvotes: 6

Related Questions