Is initialization of a memory block with NULL values equivalent with free?
Suppose I have a pointer *p which pointer to 10 memory blocks on the heap. Now, instead of free() it, I clear it manually with NULL (or '\0') like this:
for (int i = 0; i < l开发者_如何学Cength; ++i{
p[i] = '\0';
}
Is this considered a memory block is freed when every bit is cleared to zero? Or, I have to use free() to tell the operating system that the memory block is really freed and is usable (I guess)?
You do have to call free()
in order to return memory to the operating system.
A memory block filled with zeroes is no more "free" than a block full of ones.
For instance, consider a bitmap consisting only of black pixels. In most formats, the associated memory block will be filled with zeroes. Does that mean that block can be reused?
The OS has data structures in the heap that keeps track of what's allocated and where. Using malloc and free updates these structures, you cannot do it manually. You are leaking memory if you just zero the memory contents.
As long as you don't free
the memory block, it is still reserved. So, to de-allocate a block of memory (and make it available for other uses again), you need to call free
.
zero-ing out a block of memory has no impact on the allocated status of that block of memory - just on its contents.
This is not freeing of memory. This is surely a leak.
Is this considered a memory block is freed when every bit is cleared to zero?
No. It's just a memory block with zeroes as content.
I have to use free() to tell the operating system that the memory block is really freed and is usable (I guess)?
It depends. If you allocated the block with malloc
or calloc
(or other functions that state it explicitly, like strdup
), yes you need to call free()
. If you allocated the block with new
or new[]
, you need to use delete
or delete[]
, respectively, to deallocate it.
Memory that you allocated on the heap will remain allocated until you deallocate (usually free()
or delete
/[]
) it explicitly. All you are doing in your loop is using the memory, by writing data to it.
NULL value in a pointer has significance but not as a value in memory address. Assigning zero the allocated memory block has no impact on memory allocation. You have to free the memory block explicity to return to the operating system. (heap for the process)
However Memory allocated to the program is returned to Operating system when the program terminates. (Unless your program is making use of shared memory or driver's memory)
At the same time, not freeing memory may result in unexpcted termination of your program due to insufficeint memory.
Shash316
精彩评论