Search code examples
cmemory-managementunlink

Does the unlink function in C deallocate memory as well?


So I'm going through a piece of code in one of the programs and it uses an unlink function , where

hist_name = malloc(128)

However, I did notice that the program did not use a "free" to free the memory , but it did have the unlink function shown below, at the end of the program:

unlink(hist_name);

My question is , does the unlink function free memory in addition to deleting the link to the file, or do I still need to insert a free(hist_name) statement to free the memory?


Solution

  • No. hist_name is leaked. unlink won't free the parameter.

    Create a file called "a" and run this code (Compile with gcc test.c):

    #include <unistd.h>
    #include <stdlib.h>
    
    int main(void){
        char* hist_name=malloc(128);
        //Fill hist_name
        hist_name[0]='a';
        hist_name[1]='\0';
        unlink(hist_name);
    }
    

    In the following, to show you, that unlink doesn't free your allocated memory, I will use valgrind. Valgrind is a tool that allows you to detect memory leaks and other memory issues (Like out-of-bounds accesses, use of uninitialized values,etc.)

    So, if you run this program with valgrind (valgrind ./a.out), you get this output:

    ==2155== Memcheck, a memory error detector
    ==2155== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==2155== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
    ==2155== Command: ./a.out
    ==2155== 
    ==2155== 
    ==2155== HEAP SUMMARY:
    ==2155==     in use at exit: 128 bytes in 1 blocks
    ==2155==   total heap usage: 1 allocs, 0 frees, 128 bytes allocated
    ==2155== 
    ==2155== LEAK SUMMARY:
    ==2155==    definitely lost: 128 bytes in 1 blocks
    ==2155==    indirectly lost: 0 bytes in 0 blocks
    ==2155==      possibly lost: 0 bytes in 0 blocks
    ==2155==    still reachable: 0 bytes in 0 blocks
    ==2155==         suppressed: 0 bytes in 0 blocks
    ==2155== Rerun with --leak-check=full to see details of leaked memory
    ==2155== 
    ==2155== For lists of detected and suppressed errors, rerun with: -s
    ==2155== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
    

    definitely lost: 128 bytes in 1 blocks

    This means, you allocated memory once, 128 bytes, but didn't free it. ==> unlink doesn't free your memory for you.