lundi 14 avril 2014

Pointer nuances? "Free heap block modified after it was freed"


Vote count:

0




I was under the impression that in order to use delete (or delete[]), I only need to provide the address and the object type. So for example, suppose I have 10 objects of class MyClass at memory address x. I also have a global (void*) vPtr. Some time ago this happened



vPtr = (void*)(myClassPtr);


At some further point in time, those objects were no longer needed, and I wish to use that memory to store different objects, so I call



delete[] (myClass*)(vPtr);


This executes just fine. Then I go about creating my new objects and reassigning vPtr to their address



MyClass* myPtr2 = new MyClass[10];
vPtr = (void*)(myPtr2);


Now, once I'm done using the 10 MyClass objects, I wish to repurpose the memory they were using for more different objects. So I call:



delete[] (MyClass*)(myPtr2); //just like before, but this time, VS2010 breaks
//and complains about heap corruption


What am I missing? The memory trying to be freed by delete[] has to be occupied by my 10 MyClass objects, so why would there be a heap corruption? I am doubly confused because I am using this same method on objects of class MyFoo, and when I step through the code, reassigning my (void*) pointer and calling delete[] each time I wish to release the memory and create new objects, I never get complaints of heap corruption.



asked 41 secs ago






Aucun commentaire:

Enregistrer un commentaire