Search code examples
cmallocfree

Is casting free() argument to void * neccessary?


Is it neccessary to cast the value passed to free() to a void pointer in this code snippet?

free((void *) np->defn);

np is a struct in a linked list and defn is a char *.


Solution

  • C11 : 7.22.3.3 The free function

    Synopsis

    #include <stdlib.h>
    void free(void *ptr);  
    

    It means that it can take pointer to any type (void * is a generic pointer type). In general no need to cast the argument to void *, but in cases like

    int const *a = malloc(sizeof(int));
    free(a);
    

    compiler will generate a waring

    test.c: In function 'main':
    test.c:33:7: warning: passing argument 1 of 'free' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
      free(a);
           ^
    In file included from test.c:2:0:
    /usr/include/stdlib.h:151:7: note: expected 'void *' but argument is of type 'const int *'
     void  free(void *);
           ^
    

    To suppress this warning a cast is needed

     free((void *)a);