Search code examples
cmemorysegmentation-faultfree

Segmentation Fault using free() in c


I am trying to find the issue with a bit of C code that I have. The debugger says that the error occurs when I try to free the mem from a pointer:

int main(int argc, char *argv[]){   
    char *desc = malloc(30 * sizeof(char));
    if(desc == NULL)                    
    {
        fprintf(stderr, "Error - cannot allocate memory\n");
    }
    desc = "Debug this program.";
    printf("Description: %s\n", desc);
    free(desc);//break point here
    int cpid = fork();
    ....

Solution

  • You reassigned desc and then freed a pointer to a string literal, that's illegal and it causes the segmentation fault.

    You apparently failed to understand what malloc() is for, malloc() requests memory from the OS and returns a pointer to valid memory that you can use in your program.

    After you malloc() you can use the memory, but not all pointers need to me malloc()ed. For example, you can have pointers to string literals and they are useful too.

    But you can't pass anything to free() except if it was returned by malloc()/calloc()/realloc(). A pointer to a string literal or holding the address of a variable is not such a pointer, and passing it to free() is undefined behavior.

    Only use malloc() if you know that you MUST, for example to allocate a lot of memory that would overflow the stack or to allocate an unknown ammount of memory that you can calculate at runtime. Otherwise, don't.