Freeing non-malloc'd memory

Viewed 171

Let's say I declare the following array:

char *arr[3];

During running the program, depending on the user's inputs, I may or may not allocate strings of memory into this array (meaning arr[i]).

Is it safe to free(arr[i]) at the end of the program without checking which of them I allocated? Or could this cause errors?

Thanks!

2 Answers

It is safe to pass a null pointer to free, so if your array is initialized with null pointers, you can safely free all arr[i], assuming you only store pointers return by malloc() and friends and do not free them elsewhere.

Define the array as

char *arr[3] = { NULL, NULL, NULL };

or simply

char *arr[3] = { 0 };

NULL, 0 and '\0' may be used to specify a null pointer, but it is advisable to follow a simple rule of clarity:

  • use NULL for a null pointer,
  • use 0 for a null integer,
  • use '\0' for a null byte in an array of char, which is also called the null terminator.

And you can use = { 0 }; as an initializer for any C object: all elements and members will be intialized to the zero value of their type, except for unions where only the first member is initialized this way.

The only safe values to pass to free are null pointers and values returned by malloc, and to be clear on that, those values returned by malloc shall only be freed once until next time they're returned by malloc (or calloc, or realloc).

Related