0

I'm not familiar with C as much as with C++ but I found my self in need to debug C application and after even succeeded to do so, but I'm not sure if my fix indeed is correct.

Here is a code:

FcValueList **value = NULL;
value = (FcValueList **) malloc (SIZEOF_VOID_P * nobjs);

// other code...

if (value)
free (value);

The FcValueList is a structure and SIZEOF_VOID_P is a size of void pointer. The above code does not work because the value is "unable to read memory"

So I applied following fix and the code worked with app exiting with 0:

value = (FcValueList **) malloc (SIZEOF_VOID_P * nobjs);

// other code...

if (*value)
free (value);

Is my fix correct? and if not what would be correct then?

codekiddy
  • 5,897
  • 9
  • 50
  • 80

1 Answers1

6

No, your fix is not correct. Your original code is fine, but doesn't need the if statement. Passing a NULL pointer to free() is allowed.

Without more explanation, it's not really possible to give more context - your first code example is fine as shown.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Thank you so much! That worked, and I even learned something :) I can accept your answer in 7 minutes... – codekiddy Feb 16 '15 at 22:14