Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does freeing an uninitialized pointer result in undefined behavior?

Tags:

c

pointers

free

If you have a pointer that is not initialized and, by mistake, try to free it, is this going to result in undefined behavior?

Like:

int main(void){

    char *string;
    free(string);

    return 0;
}
like image 428
2013Asker Avatar asked Oct 29 '25 10:10

2013Asker


2 Answers

Does freeing an uninitialized pointer result in undefined behavior?

Yes.

However, freeing a null pointer is well-defined.

From the C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

like image 187
Oliver Charlesworth Avatar answered Oct 30 '25 23:10

Oliver Charlesworth


Yes, because accessing any uninitialised variable provokes undefined behaviour.

This includes passing an uninitialise pointer tofree(). This itself also includes the case where the uninitialise pointer "by accident" may have a value equal to NULL.

like image 38
alk Avatar answered Oct 30 '25 23:10

alk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!