0

I'm new to C++ so and I'm trying to learn it with help of examples from Wikipedia. I played with classes a bit and I have an segmentation fault error.

Here is my code:

class SomeClass {};

class AnotherClass {
    SomeClass* sc
    public:
        AnotherClass(SomeClass* SC):( sc = SC; ){}

        //***********************************************************************
        ~AnotherClass(){ delete sc; } //here I'm getting rid of internal pointer
        //***********************************************************************
};

int main( int argc, char* argv[] ) {
    SomeClass* SC = new SomeClass();
    AnotherClass* AC = new AnotherClass(SC);

    delete AC;

    // *****************************************************
    delete SC; //i think that this line might cause an error
    //******************************************************

    return 0;
}

I thought, that I should delete every pointer to get the heap memory free?! Could you please point out my mistake.

Edit:

Here is my real code:

#include <iostream>
#include <string>

using namespace std;

class Pizza {
    string dough;
    public:
        Pizza(string d):dough(d) {}
            void setDough( string value ) { dough = value; }
            string getDough() { return dough; }
};

class PizzaBuilder {
    Pizza* pizza;

    public:
        PizzaBuilder( Pizza* p ) { pizza = p; }
        ~PizzaBuilder() { delete pizza; cout << "PizzaBuilder Destructor." << endl;}

        PizzaBuilder* addExtra(string extra) { 
            string special = pizza->getDough() + " and extra " + extra;
            pizza->setDough(special);
            return this;
        }
        Pizza* getPizza() { return pizza; }
    };

int main(int argc, char* argv[]) {

    Pizza* p = new Pizza("My Special DOVE!");
    PizzaBuilder* pb = new PizzaBuilder(p);

    pb->addExtra("Mushrooms")->addExtra("Anchovies")->addExtra("Zefir")->addExtra("Chilli");

    cout << p->getDough() << endl;

    delete pb;
    delete p;

    return 0;
}
Community
  • 1
  • 1
orustammanapov
  • 1,792
  • 5
  • 25
  • 44
  • 5
    "I'm new to C++ so and I'm trying to learn it with help of examples from Wikipedia." Bad idea. Get a good book. – Sebastian Redl Sep 03 '13 at 14:31
  • you probably right :). but could tell me something about my issue? – orustammanapov Sep 03 '13 at 14:32
  • 1
    As for good books, there's a [handy list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) maintained right here on SO. – Angew is no longer proud of SO Sep 03 '13 at 14:40
  • @Angew the thing is that I'm a very slow reader, I would probably need a year to read some 100 page book :), but thanks for the list! – orustammanapov Sep 03 '13 at 14:49
  • So instead, you'd rather someone else waste a year of their time to teach you over the internet? – Crowman Sep 03 '13 at 15:01
  • @PaulGriffiths No, actually i have tried to read some, and I also try to help people myself, I thought the reason to be registered on this site is to help where you can and to get help when you need it. I don't see anything wrong about it? do you? – orustammanapov Sep 03 '13 at 15:08
  • If you can't see anything wrong with asking for help, and then moments later saying that you can't be bothered to take reasonable steps to learn, then I'm not sure what to say. – Crowman Sep 03 '13 at 15:18
  • It is always a good idea to post real code. Your code is small, so it shouldn't be too difficult to post real one. What you posted is not compilable. – AnT stands with Russia Sep 03 '13 at 15:24
  • @PaulGriffiths No.., it is not what i meant, i already read this list couple of times. i took time to read some of the books listed there and i just realized that practicing gives me more. It may depend from the fact that i'm not a native speaker or from the fact that i read slowly in general, not only programming. But I still take time to read it has nothing to do with my laziness. I didn't want to give a harsh answer: "I already saw that list, didn't help". An advantage i see here is that good answers get up voted and bad answers not. Is there other reason everyone registered here? – orustammanapov Sep 03 '13 at 15:48

3 Answers3

9

delete does not delete the pointer, as you may think. It deletes the object the pointer points to. So you are deleting the object pointed by SC twice: once from main and another from the destructor of the object pointed by AC, called automatically when deleting it.

And deleting an object more than once is undefined behavior.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • 1
    Technically, he's deleting `*SC`, the object `new`'d in the first line of `main`, twice. `SC` is a pointer (either a parameter of the constructor or a local variable of `main`). –  Sep 03 '13 at 14:34
  • @delnan: Technically you are right of course, but saying all the time: "the object pointed by `X`", or even "`*X`" is a bit tiresome. But since this question is about this particular issue, I'm updating the answer. – rodrigo Sep 03 '13 at 15:01
  • @rodrigo - writing clearly and accurately is, indeed, sometimes a bit tiresome. – Pete Becker Sep 03 '13 at 16:44
4

You need to decide who owns the object. It seems that you want AnotherClass to own the SomeClass object, given you delete it in the destructor, so therefore you shouldn't be deleteing it in main(). Double deleteing causes undefined behaviour.

The best way to avoid this would be to use std::shared_ptr, which manages multiple references to the same object in memory:

#include <memory>

class SomeClass {};

class AnotherClass {
    std::shared_ptr<SomeClass> sc
    public:
        AnotherClass(std::shared_ptr<SomeClass> SC): sc(SC){}

        //***********************************************************************
        ~AnotherClass(){ /* nothing */}
        //***********************************************************************
};

int main( int argc, char* argv[] ) {
    std::shared_ptr<SomeClass> SC(new SomeClass());
    std::shared_ptr<AnotherClass> AC(new AnotherClass(SC));


    return 0;
}

Notice the lack of calls to delete.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • What's with the `:( sc = SC; )`? – David G Sep 03 '13 at 14:37
  • @0x499602D2 Thanks; was copied from OP. Fixed now. – trojanfoe Sep 03 '13 at 14:38
  • wow, this does look confusing at first glance :). I never heard about shared pointers before, I'm just learning now. But i have noticed the way you used (<>) notation, the same way vectors using them. If i get it right they are a part of std library right? Do you know some useful links to learn more about it? I would appreciate it.. – orustammanapov Sep 03 '13 at 14:46
  • 1
    @orustammanapov Sure, here are some links: http://www.cplusplus.com/reference/memory/shared_ptr/ and http://en.cppreference.com/w/cpp/memory/shared_ptr – trojanfoe Sep 03 '13 at 14:49
2

First, try not to deal in raw pointers. Especially not when beginning C++. Try using values instead.

That said, when you pass SC to the constructor, the object stores the pointer, so it has a pointer to the same object you created in main. In the destructor, it deletes that object. Then main tries to delete the object too. Boom.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • 1
    as I stated above I'm really a newbie in this field, so what do you mean by: "using values instead"? could explain it a bit on on some short code example please? – orustammanapov Sep 03 '13 at 14:41
  • 1
    No. That's the part where you buy a book or at least use an online tutorial instead of relying on a site that is just supposed to give an overview of the language, not teach it. Showing you examples (and more importantly, giving the philosophical explanation for them) is just not an efficient use of anyone's time. – Sebastian Redl Sep 03 '13 at 15:00
  • your answer was about a using values instead of pointers. I'm not asking you to teach me the whole language, am i? I thought searching books through to find exactly the same issue i have wouldn't be efficient, I asked because i hoped there are people out there that know what is wrong with my code and it would cost 5 minutes of their precious time. If you're not willing to help just because i accepted another concrete answer, I still find no reason to make me look lazy. It did cost my time either to ask and to answer. Easier would be to look somewhere else, what i already did... – orustammanapov Sep 03 '13 at 15:24