user2195956
user2195956

Reputation: 1

Base and derived class allocation

In the code below, drvdCls derives from bseCls. This code compiles and runs as it is. I however find an issue here: newBse will get deallocated after Test() exits. Am I right?

bseCls* Test()
{

    bseCls* newBse = new drvdCls();
    drvdCls newDrvd;
    newBse = &newDrvd;
    return newBse;

}

Upvotes: 0

Views: 110

Answers (2)

Praetorian
Praetorian

Reputation: 109089

No, it won't be automatically deallocated. Every call to new must be matched by a call to delete. But that's not the only problem with your code, you're also returning the address of a local variable from the function.

newBse = &newDrvd; // memory leak, pointer to previously allocated object is lost
return newBse;     // newDrvd is destroyed when function exits, so returned
                   // pointer points to invalid memory

What you probably want to do is

bseCls* Test()
{
    return new drvdCls();
}

Now the caller must call delete on the returned pointer after using it. What you should do is

std::unique_ptr<bseCls> Test()
{
    return new drvdCls();
}

Now the allocated object will automatically be deleted when the returned unique_ptr goes out of scope.

Upvotes: 1

cdhowie
cdhowie

Reputation: 168988

The object originally pointed to by newBse will be leaked. When you assigned the address of newDrvd to newBse you are losing the pointer to the heap-allocated object, and you will not be able to delete it. This memory will be unusable until the process terminates.

Additionally, you are returning the address of a stack-allocated object as a pointer, which is bad for two reasons:

  1. The object's destructor will have been called before the function returns, meaning you would be using a pointer to a destructed object.
  2. The memory allocated for the object lives on the stack and will almost certainly be clobbered by future function calls. At that point, your pointer will be point at something that is not a bseCls, but you will be using it as though it were.

If you use the pointer returned by this function, you are invoking undefined behavior and your program has license to do anything.

Upvotes: 4

Related Questions