• Advertisement
Sign in to follow this  

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

This topic is 2915 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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
Sign in to follow this  

  • Advertisement