Freeing allocated memory: realloc() vs. free()

前端 未结 7 1157
醉梦人生
醉梦人生 2020-12-10 04:05

so I have a piece of memory allocated with malloc() and changed later with realloc().

At some point in my code I want to empty it, by this

7条回答
  •  死守一世寂寞
    2020-12-10 04:45

    I don't think you mean "empty"; that would mean "set it to some particular value that I consider to be empty" (often all bits zero). You mean free, or de-allocate.

    The manual page says:

    If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).

    Traditionally you could use realloc(ptr, 0); as a synonym for free(ptr);, just as you can use realloc(NULL, size); as a synonym for malloc(size);. I wouldn't recommend it though, it's a bit confusing and not the way people expect it to be used.

    However, nowadays in modern C the definition has changed: now realloc(ptr, 0); will free the old memory, but it's not well-defined what will be done next: it's implementation-defined.

    So: don't do this: use free() to de-allocate memory, and let realloc() be used only for changing the size to something non-zero.

提交回复
热议问题