I am not asking if I need to check to see if a pointer is NULL
before calling free
, I know I do not. Rather, I am asking whether a (typical) implementation of free
sacrifices time to check for a NULL
pointer before deallocating, or whether the nature of the process does not actually invoke any additional overhead. For example, someone knowing what free
does might imagine that its implementation might be something like this:
void free(void* ptr){
if(ptr != NULL){
<proceed with deallocation>
}
}
But this contradicts the C philosophy of not paying for what I don't use: if I know I will not pass a NULL
pointer to free
, there should not be a performance deficit as a result. Thus, I am pretty sure that free
does not usually invoke such a cost, and in that case I would like to know how/why. I tried searching for the answer to this but I saw a hurricane of questions asking whether deleting a NULL
pointer was safe instead.
EDIT: I am already satisfied with the answers and comments, though for future reference I want to make clear what it is I was asking. I was not asking from a programmer's perspective what the state of the program and my NULL
pointer are after I call free
on it. I was more interested in the perspective of the heap manager. To give an example of what I mean, suppose I am at a bakery and it is my job to take whatever is at the table and dump it all in the trash. It could be 5 brownies, a dozen cookies, or whatever, and yes I know this is not the best analogy but bear with me. I wanted to know if there could exist heap managers that, if for instance, there was "nothing" on the table whether my dumping "nothing" into the trash would make any difference, which would be an implicit handling of "nothing." An explicit handling of "nothing" would be my checking of the table to see if anything is on it before I try to dump it. I wanted to know if heap managers could usually handle the situation implicitly, i.e., by doing the same thing that they would normally do and incidentally also handling a NULL
pointer, or explicitly, by making an explicit check to see if a pointer is NULL
. As awksp's comment reveals, since it is required that nothing literally be done in the case of a NULL
pointer, it must be true that an explicit check exists because treating the NULL
pointer the same as the others would not be a no-op, and therefore we must check for NULL
explicitly beforehand.