Search code examples
c++delete-operator

Getting an error on delete[] of vector element using C11 style for loop


#include <iostream>
#include <vector>
using namespace std;

// Shows Factor Design Pattern
class Stooge{
    public:
        static Stooge* makeStooge(int choice); // static class function
        virtual void slapStick() = 0; // implemented by derived
        virtual ~Stooge(){}
};

class Larry : public Stooge{
    public:
        void slapStick(){
           cout << "Larry: poke eyes" << endl; 
        }

        ~Larry(){}
};

class Moe : public Stooge{
    public:
        void slapStick(){
           cout << "Moe: slap head" << endl; 
        }
        ~Moe(){}
};

class Curly : public Stooge{
    public:
        void slapStick(){
           cout << "Curly: suffer abuse" << endl; 
        }
        ~Curly(){}
};

Stooge* Stooge::makeStooge(int choice){
    switch(choice){
        case 1: return new Larry;
                break;
        case 2: return new Moe;
                break;
        case 3: return new Curly;
                break;
        default:{
                    cout << "Enter valid choice next time!!";
                    return NULL;
                }
    }
}

int main(){

    vector<Stooge*> roles;
    int choice;

    while(true){
        cout << "Larry(1) Moe(2) Curly(3) Exit(0)" << endl;
        cin >> choice;

        if(choice==0)
            break;

        Stooge *s = Stooge::makeStooge(choice);

        if(s)
            roles.push_back(s);
    }

    for(auto r : roles)
        r->slapStick();

    // this will fail
    for(auto x : roles)
        delete[] x;

    // this works 
    #if 0
    for(int i=0; i<roles.size(); i++)
        delete roles[i];
    #endif

    return 0;
}

When I run the above snippet I get a crash with the following error message:

a.out(48873,0x7fff75912000) malloc: *** error for object 0x7fab72500058: pointer being freed was not allocated

In the call stack for delete[] I see a valid (malloc'ed) address for 'x' , but cant understand why there is problem in the actual free Contrast to that the regular for loop (without the C11 feature works fine). Which means I don't fully understand how to use the auto-for loop feature - can somebody please explain?


Solution

  • x is a single element in roles. Since it was allocated with new, it should be freed with delete (like the second block does), and not delete[].