Should I free memory in C if it is not allocated properly?
You shouldn't, because you can't, because it turns out the question doesn't even make sense.
malloc
either gives you a pointer to properly-allocated memory, or it doesn't.
Those two cases are distinct: It either gives you a non-null pointer, or a null pointer.
A null pointer return means that malloc
failed, and did not allocate any memory for you.
Suppose that in the process of trying but failing to allocate the memory that you asked for, malloc
did partially allocate some memory, or something. Suppose it was your job to free this. How would you do this? You have no way of referring to that memory! When malloc
fails, it returns you a null pointer, and a null pointer points, by definition, nowhere.
It doesn't make much sense to pass a null pointer to the free
function. Once upon a time, this was an error, and tended to crash. Today, it's harmless: free
checks to see if you've handed it a null pointer, and if so, it quietly does nothing.
So in fact, if malloc
partially allocates memory or something, then fails, it has to be malloc
's job to clean that up automatically, before returning the null pointer to you.