简体   繁体   中英

Does freeing an uninitialized pointer result in undefined behavior?

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;
}

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 .

Yes, because accessing any uninitialised variable provokes undefined behaviour.

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

Yes, it is undefined behavior.

The pointer passed to free should be a pointer to a valid object allocated with malloc , calloc , realloc or a null pointer.

From C99:

(7.20.3.2p2) "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."

是的,确实如此,因为您应该只free() 1.为NULL或2.是通过调用malloc()calloc()realloc()获得的指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM