24
// Assume class definition for Cat is here.

Cat makeCat() {
    Cat lady = new Cat("fluffy");
    return lady;
}

int main (...) {
    Cat molly = makeCat();
    molly->eatFood(); 
    return 0;
}

Will there be a "use after free" error on molly->eatFood()?

10
  • 2
    Kevin: read about STL auto_ptr and boost shared_ptr. Sep 8, 2010 at 14:56
  • 16
    No, don't read about STL until you understand the basics first.
    – James
    Sep 8, 2010 at 15:07
  • 4
    @James: I wish we could down-vote comments. Do you need to understand how memory management works in BASIC in order to be able to write BASIC code? First teaching students to do everything manually and then teaching them that doing it manually is bad and that they need to unlearn everything they learned and learn better was is not exactly helpful.
    – sbi
    Sep 8, 2010 at 15:16
  • 1
    Kevin, this code still can't compile.
    – sbi
    Sep 8, 2010 at 15:17
  • 2
    @sbi: I tend to agree. However, in this case, I think @James was talking about the basics of C++ syntax, not about memory management. The OP is probably coming from C# so learning at least the differences with C# and what a pointer is can not harm.
    – ereOn
    Sep 8, 2010 at 15:25

7 Answers 7

28

Corrected your program and created an example implementation of class Cat:

#include <iostream>
#include <string>

class Cat {
public:
        Cat(const std::string& name_ = "Kitty")
        : name(name_)
        {
                std::cout << "Cat " << name << " created." << std::endl;
        }
        ~Cat(){
                std::cout << "Cat " << name << " destroyed." << std::endl;
        }
        void eatFood(){
                std::cout << "Food eaten by cat named " << name << "." << std::endl;
        }
private:
        std::string name;
};

Cat* makeCat1() {
        return new Cat("Cat1");
}

Cat makeCat2() {
        return Cat("Cat2");
}

int main (){
        Cat kit = makeCat2();
        kit.eatFood();

        Cat *molly = makeCat1();
        molly->eatFood();
        delete molly;

        return 0;
}

It will produce the output:

Cat Cat2 created.
Food eaten by cat named Cat2.
Cat Cat1 created.
Food eaten by cat named Cat1.
Cat Cat1 destroyed.
Cat Cat2 destroyed.

I suggest you learn a basic book about the C++ cover to cover before continuing.

5
  • 5
    ...although it may produce a different output since the C++ standard doesn't require a compiler to elide unnecessery copies whenever possible. So, it's entirely possible to see another two "Cat Cat2 destroyed" messages (no RVO, for example)
    – sellibitze
    Sep 8, 2010 at 20:32
  • makeCat1 returns a pointer, and makeCat2 returns a reference?
    – qed
    Nov 9, 2013 at 21:46
  • What is : name(name_) for in the constructor Cat?
    – qed
    Nov 9, 2013 at 21:51
  • This is called constructor initializer list. This one has one element: the initialization if the name data member with the name_ parameter. It is after the parameter list of the constructor, begins with a colon and its elements are separated by commas. en.cppreference.com/w/cpp/language/initializer_list
    – Notinlist
    Nov 10, 2013 at 0:23
  • @qed makeCat2 creates a value (nor a reference neither a pointer). This output tells that the copying of it was optimized out. It behaves like it were created directly in main and never copied.
    – Notinlist
    Nov 10, 2013 at 13:25
8

new Cat("fluffy") creates a pointer. You will need to specify Cat* as return type. Since the object is created in heap, it will still be available after the function returned.

1
  • 1
    It is still available when created on the stack as it is returned by value (ie copy constructed back (though the compiler is allowed to elide the copy)). So apart from the syntax error the code is fine as written and does not use a destroyed object. Sep 8, 2010 at 18:17
5

There is no error as far as invalid use of memory other than a memory leak at the end of your program. If something is created on the heap (such as with new) then you need to call delete on it to free it.

You also have a lot of syntax errors, corrected below.

Cat* makeCat() 
{
  Cat *lady = new Cat("fluffy");
  return lady;
}

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

  Cat* molly = makeCat();
  molly->eatFood(); 

  delete molly;//This was added
  return 0;
}
5
  • Can one leak memory when the program terminates?
    – Eiko
    Sep 8, 2010 at 14:54
  • 1
    @Eiko: Usually the OS will free it but this is not guaranteed. For anything that is not guaranteed it's highly unrecommended to do it. Especially with not freeing memory. For example who says an important piece of code doesn't exist in the destructor. Sep 8, 2010 at 23:22
  • I agree that it's wise to clean up after yourself - and with clean code it's not much work anyway. (Although I sometimes read the advice to not waste those CPU cycles)
    – Eiko
    Sep 8, 2010 at 23:41
  • @Eiko: " I sometimes read the advice to not waste those CPU cycles" - Ignore that advice it is bad advice written by someone unexperienced. Sep 8, 2010 at 23:52
  • Be careful. In some very rare conditions it worth not doing a cleanup, but killing yourself. If you delete all allocated memory while you were swapped out by OS, then the closing of the program will eat up a load of resources and user time. The software must be able (compiling option) to exit cleanly, but sometimes it is really good to commit suicide. :-) For example I would welcome it in Firefox and Outlook and some...
    – Notinlist
    Sep 9, 2010 at 11:50
4

Since lady is created on the heap (with a new), it will not be destroyed when you exit the makeCat method. So the call on molly is perfectly valid.

BUT, you have a memory leak. You need to delete molly after using it (sometime in the future.) Since your program ends, this is not a big deal. In a larger program, this would be a very big deal.

3

If your complier supports c++11 you can use unique_ptr here:

#include <iostream>
#include <memory>

using namespace std;
class Cat {
    public:
        Cat() {
            cout << "Cat created" << endl;
        }
        ~Cat() {
            cout << "Cat destroyed" << endl;
        }
        void eatFood() {
            cout << "Cat is eating food" << endl;
        }
};

unique_ptr<Cat> makeCat() {
    unique_ptr<Cat> lady( new Cat );
    return lady;
}

int main () {
    unique_ptr<Cat> molly = makeCat();
    molly->eatFood();
    return 0;
}

Now, you don't have to worry about deleting created object. It will be deleted as soon as molly pointer goes out of scope:

Cat created
Cat is eating food
Cat destroyed
2

The problem is not a "Use after Free"; more probably that you're not delete-ing the new instance.

0

I think it should be Cat *lady and Cat *molly, but else it should be ok.

3
  • When I return the object sally, isn't that pass-by-value? If yes, won't sally get deleted after the function ends? Sep 8, 2010 at 14:55
  • If by 'sally' you mean the 'lady' variable inside of makeCat, no.
    – MerickOWA
    Sep 8, 2010 at 14:56
  • You actually pass a pointer (but you missed the "*" in your code.
    – Eiko
    Sep 8, 2010 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.