Does freeing an uninitialized pointer result in undefined behavior?

大兔子大兔子 提交于 2019-12-20 03:02:08

问题


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

回答1:


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.




回答2:


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.




回答3:


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."




回答4:


Yes, it does, since you should only free() a pointer that 1. is NULL or 2. you obtained via a call to malloc(), calloc() or realloc().



来源:https://stackoverflow.com/questions/18160776/does-freeing-an-uninitialized-pointer-result-in-undefined-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!