开发者

How free handles null pointer [duplicate]

开发者 https://www.devze.com 2023-03-12 16:05 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: checking for NULL before calling free
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

checking for NULL before calling free

What happens when you try to free() already freed memory in 开发者_开发技巧c?

Hope this isn't a totally dumb question. Anyway...

What happens when a null pointer is passed to free.

Thank you!

P.S. What about a standard compliant allocator? Thanks again!


It immediately returns without doing anything.

Per 7.20.3.2, paragraph 3:

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.


The man page says:

free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.


free(ptr) should do nothing if ptr is NULL.

In the real-world programming, this feature helps make your code even simpler like this:

class YourClass
{
public:

YourClass()
{
    m_ptr = (int*)malloc(sizeof(int));

    //Validate m_ptr and perform other initialization here
}

~YourClass()
{
    // You don't have to validate m_ptr like this
    // if (m_ptr)
    // {
    //     delete m_ptr;
    // }

    // Instead, just call free(m_ptr)
    // Notice: generally you should avoid managing the pointer by yourself,
    // i.e., RAII like smart pointers is a better option.
    free(m_ptr);
}

private:

int *m_ptr;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号