#include <iostream>
#include <vector>
using namespace std;
struct Test
{
int a;
float b;
char* c;
};
int main()
{
vector<Test*> first;
vector<Test*> second;
for(unsigned int i = 0; i < 2; i++)
{
Test* pTest = new Test;
pTest->a = i;
pTest->b = 2.0;
pTest->c = "Hello world!";
first.push_back(pTest);
second.push_back(pTest);
}
for(vector<Test*>::iterator it = first.begin(); it != first.end();)
{
Test* pTest = *it;
if(pTest->a == 1)
{
if(second[1] == pTest)
{
cout << "Pointers are equal!" << endl;
}
else
{
cout << "Pointers are NOT equal!" << endl;
}
it = first.erase(it);
delete pTest;
cout << "Pointer value: " << pTest << endl;
// Program should crash here, but doesn't?
cout << "Test.c value: " << pTest->c << endl;
}
else
{
it++;
}
}
cout << first.size() << endl;
cout << second.size() << endl;
return 0;
}
[C++] Deleting struct doesn't work?
I'm probably missing something obvious here. Can anyone tell me what it is? Thanks.
It shouldn't necessarily crash, it's undefined behaviour. It might work, it might give gibberish output or it might crash.
Aha...
I've edited the code above to make it easier to read (i.e. got rid of the escaped quotation marks) and also put the comment on the right line, where the dereference is. Still sounds like it would be undefined behavior though, right?
I've edited the code above to make it easier to read (i.e. got rid of the escaped quotation marks) and also put the comment on the right line, where the dereference is. Still sounds like it would be undefined behavior though, right?
Are you talking about your comment about how the program "should crash here, but doesn't?" That is a bad assumption on your part. There's no reason the program should crash there -- it just invoked undefined behavior. Undefined behavior does not necessarily mean "crash."
Agreed, it was a bad assumption on my part. I was not aware (or had forgotten) that the behavior is undefined. Thanks again. :)
Page heap mode can catch certain memory errors, but because it's OS level and only works at page granularity, it's unlikely to flag a bug like this, which happens entirely within a still-allocated page. If you have control of the source code, the easiest way to catch these things is with Valgrind under linux, or the Debug heap under MSVC. (MingW and Mac users, I got nuthin' for you.)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement