Search code examples
cpointersfree

Invalid (Aborted)core dumped error while using free() in C


here's the code: can anyone explain this issue how can i deallocate the memory of s in main

char *get(int N)
{
    char *s=malloc(10*sizeof(char));  
    s="hello";  
    return s;  
}
 int main()  
{  
    char *s=get(4);  
    printf(s);  
    free(s);  
}

Solution

  • This here:

    s="hello";
    

    Doesn't write "hello" to the allocated memory. Instead, it reassigns s to point to a read-only place where "hello" is stored. The memory you allocated with malloc is leaked, and the free(s); is invalid, because you can't free that read-only memory.

    If you want to copy "hello" into s, try strcpy(s,"hello"); instead.