I am trying to free dynamically allocated memory using free(), but I found that what it does is to have the argument pointer point to some new location, and leaving the previously-pointed-at location as it was, the memory is not cleared. And if I use malloc again, the pointer may point to this messy block, and it’s already filled with garbage, which is really annoying..
I’m kinda new to C and I think delete[] in c++ doesn’t have this problem. Any advise?
Thanks
Why is having newly allocated memory filled with garbage “really annoying”? If you allocate memory, presumably it’s because you’re going to use it for something — which means you have to store some meaningful value into it before attempting to read it. In most cases, in well-written code, there’s no reason to care what’s in newly allocated memory.
If you happen to have a requirement for a newly allocated block of memory you can call
memsetafter callingmalloc, or you can usecallocinstead ofmalloc. But consider carefully whether there’s any real advantage in doing so. If you’re actually going to use those all-bits-zero values (i.e., if all-bits-zero happens to be the “meaningful value” I mentioned above), go ahead and clear the block. (But keep in mind that the language doesn’t guarantee that either a null pointer or a floating-point 0.0 is represented as all-bits-zero, though it is in most implementations they are.)And
free()doesn’t “have the argument pointer point to some new location”.free(ptr)causes the memory pointed to byptrto be made available for future allocation. It doesn’t change the contents of the pointer objectptritself (though the address stored inptrdoes become invalid).