Thursday, July 9, 2009

Vector of pointers crashes on delete

I have a java gui which calls a C++ dll which in turn calls another C++ dll. Both dlls are built using Microsoft Visual C++ 6.0;
Both dlls contain functions which take in 4 vectors. The first dll function calls the second dll function.
The first 2 vectors are source parameters and the last 2 are result vectors. All vectors contain the same number elements.
The function call in the first dll looks something like this:

convert(std::vector& firstVector, std::vector& secondVector, std::vector& thirdVector, std::vector& fourthVector)
{
thirdVector.reserve(10);
fourthVector.reserve(10);

C2DLL* c2dll = new c2dll();
c2dll->convert(firstVector, secondVector, thirdVector, fourthVector);

.
.
.
.
.
.
.

for(int i = 0; i < 10; i++)
{
delete firstVector[i];
}
firstVector.clear();

for(int i = 0; i < 10; i++)
{
delete secondVector[i];
}
secondVector.clear();

for(int i = 0; i < 10; i++)
{
delete thirdVector[i];
}
thirdVector.clear();

for(int i = 0; i < 10; i++)
{
delete fourthVector[i];
}
fourthVector.clear();
}


void C2DLL::convert(std::vector& firstVector, std::vector& secondVector, std::vector& thirdVector, std::vector& fourthVector)
{
for(int i = 0; i < 10; i++)
{
thirdVector.push_back(new Class2()); /// Class2 is a subclass of Class1
fourthVector.push_back(new ClassA());
}
}


Everything was running great until I would get to deleting each element of the fourthVector. The application would crash. For the life of me I could not figure out why. I finally did some Google searching and figured out it was the compiler settings.
Each dll needs to be built with the /MD option. To set this, go to the project settings, C/C++ tab, Code Generation Category. Select Debug Multithreaded DLL.
Apparently this allocates the memory used in each dll on the local heap. Before changing this setting, I was using Debug Mutithreaded. Since the memory for the fourth vector was allocated in the second C++ dll, the memory was not on the local heap for the first dll, which was where the memory was being deallocated.
C++ Memory, what a pain in the butt.


More C++

No comments: