Does freeing an uninitialized pointer result in undefined behavior?

前端 未结 4 1328
悲&欢浪女
悲&欢浪女 2021-01-21 09:39

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){

             


        
4条回答
  •  悲哀的现实
    2021-01-21 10:34

    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.

提交回复
热议问题