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 I mean essentially give it memory of 0. Something which would intuitively be done with realloc(pointer,0)
. I have read on here that this is implementation defined and should not be used.
Should I instead use free()
, and then do another malloc()
?
Use
free()
to free, to release dynamically allocated memory.Although former documentations state that
realloc(p, 0)
is equivalent tofree(p)
, the lastest POSIX documentation explictly states that this is not the case:And more over:
I would use realloc to give a pointer more or less memory, but not to empty it. To empty the pointer I would use free.
realloc()
is used to increase or decrease the memory and not to free the memory.Check this, and use
free()
to release the memory (link).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:
Traditionally you could use
realloc(ptr, 0);
as a synonym forfree(ptr);
, just as you can userealloc(NULL, size);
as a synonym formalloc(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 letrealloc()
be used only for changing the size to something non-zero.It depends on what you mean: if you want to empty the memory used, but still have access to that memory, then you use
memset(pointer, 0, mem_size);
, to re-initialize the said memory to zeroes.If you no longer need that memory, then you simply call
free(pointer);
, which'll free the memory, so it can be used elsewhere.Using
realloc(pointer, 0)
may work likefree
on your system, but this is not standard behaviour.realloc(ptr, 0)
is not specified by the C99 or C11 standards to be the equivalent offree(ptr)
.realloc(pointer, 0)
is not equivalent tofree(pointer)
.The standard (C99, §7.22.3.5):
As you can see, it doesn't specify a special case for realloc calls where the size is 0. Instead, it only states that a NULL pointer is returned on failure to allocate memory, and a pointer in all other cases. A pointer that points to 0 bytes would, then, be a viable option.
To quote a related question:
As another answer on that linked question states, the behaviour of
realloc(ptr, 0)
is explicitly defined as implementation defined according to the current C11 standard:Use
free(pointer); pointer = 0
instead ofrealloc(pointer, 0)
.