Can calling memset on a dynamically allocated memory cause heap corruption
While debugging a segmentation fault in a real project, where the crash happens after a long run with random testing which are not easy to reproduce. Crash point shows crash in a function which is written something like
void deallocateObject( objectType* ptr)
{
ASSERT(ptr);
if(!ptr)
return;
if(ptr->customDeallocator)
ptr->customDeallocator->deallocate();
else
free(ptr);
}
There are various kind of allocator and deallocator being used in the project. To just verify that the segmentation fault is not because of allocated memory not being set to NULL after deallocation, I added a call to memset after the last statement in this function.
memset(ptr, 0, sizeof(objectType));
But after this change I started getting crash every time with message saying heap is corrupted.
So my question is how and in what scenario a call to memset() can cause heap corruption.
So my question is how and in what scenario a call to memset() can cause heap corruption.
Any time you use it to modify memory that might be being used to track the internal structure of the heap. For example, memory that you just told the heap allocator that you were finished with and that it was now free to use for any purpose such as, for example, tracking the internal structure of the heap.
To just verify that the segmentation fault is not because of allocated memory not being set to NULL after deallocation
Well, that's not how you debug dynamically allocated memory related problem. A pointer containing NULL
is as invalid as a pointer which has been already passed to free()
memory, in terms of further deallocation.
So, whether an already free()
-d pointer is (manually) set to NULL
or not, further usage (dereference) of that pointer will cause undefined behavior, you may or may not get a segmentation fault, for certain, it's just one of many side effects of having UB.
You need to use a memory debugger, like valgrind to catch and resolve the issue.
FWIW, any attempt of using invalid memory (including NULL
, yes) invokes UB, avoid that.
上一篇: C ++在某些情况下删除崩溃