Sign in to follow this  
RobAU78

[C++] Deleting struct doesn't work?

Recommended Posts

RobAU78    206
I'm probably missing something obvious here. Can anyone tell me what it is? Thanks.
#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;
}



Share this post


Link to post
Share on other sites
RobAU78    206
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?

Share this post


Link to post
Share on other sites
jpetrie    13157
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."

Share this post


Link to post
Share on other sites
RobAU78    206
Agreed, it was a bad assumption on my part. I was not aware (or had forgotten) that the behavior is undefined. Thanks again. :)

Share this post


Link to post
Share on other sites
Sneftel    1788
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.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this