Delete object after using it in function C++ - c++

I have a question about delete and memory leak in C++. Considered the code below:
class AnObject{
public:
AnObject* Foo(){
// how can I delete this object ???
AnObject* obj = new AnObject();
...
return obj;
}
};
int main(){
...
AnObject* x = new AnObject();
AnObject* result = x->Foo();
delete x;
return 0;
}
My question is how can I delete the pointer in fuction AnObject::Foo() ???
// I read some suggestions who required changing the function, don't create an object with the word new in a fucntion. But does it exist a method to delete this pointer ?

You would do so by deleting this within AnObject::Foo but I would strongly discourage you from doing so. In this case, you do not need pointers at all:
class AnObject{
public:
AnObject Foo(){
return AnObject{};
}
};
int main()
{
AnObject x{};
AnObject result = x.Foo();
return 0;
}
If for whatever reason you really do need pointers, consider smart pointers
#include <memory>
class AnObject{
public:
std::unique_ptr<AnObject> Foo(){
return std::make_unique<AnObject>();
}
};
int main()
{
std::unique_ptr<AnObject> x = std::make_unique<AnObject>();
std::unique_ptr<AnObject> result = x->Foo();
return 0;
}
In both cases, you do not need to delete anything as you are using RAII semantics to handle your memory cleanup via scope.

Related

Memory leak after pointing to NEW object

struct StructA {
StructA(parameters) { ... } //StructA onstructor
};
struct StructB {
StructA *pObjectA;
int counter = 0;
void function() {
if (counter < 1) { pObjectA = new StructA[100]; }
pObjectA[counter] = *new StructA(parameters); //Memory leak here
counter++;
}
};
struct StructC {
StructB objectB;
~StructC() { //StructC destructor
delete[] objectB.pObjectA;
objectB.pObjectA = NULL;
}
};
int main() {
StructC objectC;
for (int i = 0; i < 900; i++) {
objectC.objectB.function();
}
return 0;
} //Struct C destructor here
I need to create an object array and then, with each call to objectB.function(), to pass specific parameters to the constructor of StructA. The code above works perfectly, except for the memory leak, which I am unable to get rid of.
My guess is that the StructC destructor deletes only the object array, not each *new StructA(parameters). I tried to play around with pointers and delete[] a little bit, but all I got was access memory violation errors. This is the only way I can think of that works. All help appreciated.
A class destructor should release resources that were acquired in its constructor. It seems like you wanted to defer deleting an array allocated in one class to the destructor of a second class. Thats never a good idea. In the best case you dont have to do anything in the destructor because you use automatic storage (means what the name suggest: memory is managed automatically).
Your code could look like this:
struct StructA {
StructA(parameters) { ... } //StructA onstructor
};
struct StructB {
std::vector<StructA> pObjectA;
int counter = 0;
void function() {
if (counter < 1) { pObjectA.reserve(100); }
pObjectA.emplace_back(parameters);
counter++;
}
};
struct StructC {
StructB objectB;
};
int main() {
StructC objectC;
for (int i = 0; i < 900; i++) {
objectC.objectB.function();
}
return 0;
}
Note that I tried to keep the structure as is maybe there are other things to change. For example you dont need counter, as you can use std::vector::size to query the number of elements in the vector.
PS: As you already noticed, this is a memory leak:
pObjectA[counter] = *new StructA(parameters); //Memory leak here
It is not really clear why you wrote that code in the first place. The idomatic way to create an object of type StructA is StructA a; (no new!).
As you correctly assumed, memory leaks are caused by not properly cleaning up all new with corresponsing delete. However in idiomatic C++ there's no use to use new and delete directly.
Use std::vector, std::shared_ptr and std::unique_ptr to let RAII keep track of dynamically created objects, references to them and when to clean up. Not only is it more robust, it's also a lot shorter and easier to read.
With your code's general overall structure:
#include <memory>
#include <vector>
struct StructA {
};
struct StructB {
std::vector<std::shared_ptr<StructA>> objectAs;
void function() {
objectAs.push_back(
std::make_shared<StructA>( /*parameters*/ )
);
}
};
struct StructC {
StructB objectB;
};
int main() {
StructC objectC;
for (int i = 0; i < 900; i++) {
objectC.objectB.function();
}
return 0;
}

C++ disallow stack instance but allow new delete

Basically what I want is:
class MyClass{
public:
MyClass() = default;
// what should I do?
}
MyClass mc; // compile time error;
auto pmc = new MyClass; //OK
delete pmc; //OK too
I know I can make it heap-only by hiding constructor (can not new outside of the class now) or hiding destructor (can not delete outside of the class now) or hiding both. What if I don't want to introduce some new named function and just want the good old new and delete? Is it possible (even with hack)?
My "like a smart pointer, but not" idea:
#include <iostream>
class MyClass_ {
private:
/**/ MyClass_( void ) { }
/**/ ~MyClass_( void ) { }
public:
void func( void ) const { std::cout << "Hello" << std::endl; }
friend class MyClass;
} ;
class MyClass {
public:
/**/ MyClass( void ) : p( new MyClass_ ) { }
/**/ ~MyClass( void ) { delete p; }
// Tricky implementation details follow...
// The question in all cases is, who owns the MyClass_ that has been
// allocated on the heap? Do you always allocate a new one, and then
// copy the guts? (That might be expensive!) Do you change ownership?
// Then what about the other MyClass? What does it point to?
// Or do you share ownership? Then you need to ref-count so you don't
// delete too soon. (And this whole thing turns into an ordinary
// shared_ptr<MyClass_>)
/**/ MyClass( const MyClass &o ) { }
/**/ MyClass( MyClass &&o ) { }
MyClass &operator=( const MyClass &o ) { }
MyClass &operator=( MyClass &&o ) { }
MyClass_ * operator->( void ) { return p; }
const MyClass_ * operator->( void ) const { return p; }
private:
MyClass_ *p;
} ;
int
main( int, char ** )
{
MyClass a; // this will be destroyed properly
MyClass *b = new MyClass; // this will leak if you don't delete it
a->func( );
(*b)->func( );
return 0;
}
This is going to sound like not-what-you-want, but surround it in another class. That way you can enforce your storage is allocated off of the heap, and keep such details away from your API user.
A usual way would be to make your constructor private, and add some static member function (you could call it a factory or making function) which returns a pointer.
So your class would look like
class MyClass{
private:
MyClass() = default;
public:
static MyClass* make() { return new MyClass; };
// what should I do?
}
and you'll code:
auto mc = MyClass::make();
elsewhere (instead of new MyClass)
etc. However be aware of the rule of five and consider using (as return type of your MyClass::make) some smart pointer from the <memory> header.
You could also define your own smart pointer class with its own unary operator -> and operator * and your own variadic templates inspired by std::make_shared ...
just want the good old new and delete
In genuine C++11, this is frowned upon and may be considered bad style. You should avoid using explicitly new outside of your library, and adopt some smart pointer way of coding.

Smartpointers equivalent

There is an equivalent codification in C++ with smartpointers for this code?
In External.cpp:
class ExampleClass {...};
ExampleClass* function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return ptr;
}
In Another.cpp i would like to do something like this properly, how?:
ExampleClass *ptr2 = function();
There are two actually, you could use either unique_ptr or shared_ptr, look here when to use which: Which kind of pointer do I use when?
I'f you'd opt for the unique_ptr, then you'd get:
class ExampleClass {...};
std::unique_ptr<ExampleClass> function()
{
std::unique_ptr<ExampleClass> uptr = std::make_unique<ExampleClass>();
uptr->doSomething();
return std::move(uptr);
}
//In Another.cpp
std::unique_ptr<ExampleClass> ptr2 = function();
//you could even store the result in a shared pointer!!
std::shared_ptr<ExampleClass> ptr3 = function();
I won't really recommend it, but you can return an object that implicitly converts to a raw pointer. It will own it for a short duration, and delete if no-one grabs it.
struct RelinquishOrDelete {
ExampleClass *_ptr;
operator ExampleClass*() { auto ret = _ptr; _ptr = nullptr; return ret; }
~RelinquishOrDelete() {
if(!_ptr) {
cerr << "returned object wasn't taken by a new owner\n";
delete _ptr;
}
}
};
Using it is simple. It will pack and unpack the pointer in this simple case:
RelinquishOrDelete function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return {ptr};
}
// ...
ExampleClass *ptr2 = function();
But of course, it will likely cause unexpected behavior if used in this perfectly reasonable piece of code:
auto ptr3 = function();
A smart pointer with much stricter ownership semantics is really the best approach.

Example of memory leak in c++ (by use of exceptions)

In C++ How to program there is a paragraph that say:
A common programming practice is to allocate dynamic memory, assign the address of
that memory to a pointer, use the pointer to manipulate the memory and deallocate the
memory with delete when the memory is no longer needed. If an exception occurs after
successful memory allocation but before the delete statement executes, a memory leak
could occur. The C++ standard provides class template unique_ptr in header to
deal with this situation.
Any on could introduce me a real example that exception occur and memory will leak like this post?
A bit more subtle example.
Take an naive implementation of a class that holds two dynamically allocated arrays:
struct Foo {
private:
int* first;
int* second;
public:
Foo()
: first(new int[10000])
, second(new int[10000])
{ }
void Bar() { throw 42; }
~Foo()
{
delete [] first;
delete [] second;
}
};
int main()
{
Foo f;
/* more code */
}
Now, if we get an exception because we call method Bar somewhere, everything's fine - the stack unwinding guarantess that f's destructor gets called.
But if we get a bad_alloc when initializing second, we leak the memory that first points to.
class MyClass
{
public:
char* buffer;
MyClass(bool throwException)
{
buffer = new char[1024];
if(throwException)
throw std::runtime_error("MyClass::MyClass() failed");
}
~MyClass()
{
delete[] buffer;
}
};
int main()
{
// Memory leak, if an exception is thrown before a delete
MyClass* ptr = new MyClass(false);
throw std::runtime_error("<any error>");
delete ptr;
}
int main()
{
// Memory leak due to a missing call to MyClass()::~MyClass()
// in case MyClass()::MyClass() throws an exception.
MyClass instance = MyClass(true);
}
See also: C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
void func()
{
char *p = new char[10];
some_function_which_may_throw(p);
delete [] p;
}
If the call to some_function_which_may_throw(p) throws an exception we leak the memory pointed to by p.
Simple example
try {
int* pValue = new int();
if (someCondition) {
throw 42;
}
delete pValue;
} catch (int&) {
}
To have a less contrived example, I recently found this potential leak in my code when allocating nodes with a given allocator object.
std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type^ v) {
char* buffer = al.allocate(sizeof(node)); //allocate memory
return std::unique_ptr<node>(al.construct(buffer, v),{al})); //construct
}
It's less obvious how to fix this because of the buffer, but with help I got it:
struct only_deallocate {
allocator* a;
size_type s;
only_deallocate(allocator& alloc, size_type size):a(&alloc), s(size) {}
template<class T> void operator()(T* ptr) {a->deallocate(ptr, s);}
operator alloc_aware() const {return alloc_aware(*a, s);}
};
std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type& v) {
std::unique_ptr<node, only_deallocate> buf(alloc.allocate(sizeof(node)),{alloc, sizeof(node)});//allocate memory
alloc.construct(buf.get(), value);
return std::unique_ptr<node,alloc_aware>(std::move(buf));
}
Compiling Code here

Static factory methods and static objects memory leaks

I have a class with a static factory constructor which returns a pointer to the object created.
I have to declare the object as a static object inside a namespace but I don't know how to delete it correctly
class Foo
{
public:
Foo(int, int* );
virtual ~Foo();
static Foo* MyFooInitializer(int n )
{
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
Foo *ret = new Foo(n,p);
delete p;
return ret;
}
int someFooFunction(int a);
}
Then in my namespace I have a static inline function
namespace MyNamespace
{
static inline void myfunction()
{
static Foo *foo1 = Foo::MyFooInitializer(10);
int y = somevalue();
int x = foo1->someFooFunction(int y);
}
}
I obviously have a memory leak here because the object is never deleted.
The important fact is that I need that foo1 is declared as static because once created it must be the same object during all the program and must be unique (it keeps track of some variables).
Probably this is a design problem, but I don't know how to delete it when my program exits or when I explicitly want to delete it to reinitialize it.
SOLUTION:
I modified the body of MyFooInitializer this way:
static Foo* MyFooInitializer(int n )
{
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
static Foo ret = Foo(n,p);
delete[] p;
return &ret;
}
This allows me to release all the memory correctly when the program terminates. Valgrind says all the heap memory is freed!
There is no need for allocating that Foo on the heap here:
static Foo* MyFooInitializer(int x) {
static Foo some_foo(x);
return &some_foo;
}
There are no leaks in that code, that Foo will be destroyed when your program ends.
Note that if the pointer returned by MyFooInitializer actually points to some class which inherits from Foo, then you'd just have to use the derived type for the static variable:
static Foo* MyFooInitializer(int x) {
static SomeFooDerived some_foo(x);
return &some_foo;
}
Edit: Since you provided the actual function body, my answer is valid. You'd do it like this:
static Foo* MyFooInitializer(int n ) {
// Don't know what this p is, anyway...
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
static Foo ret(n,g); // what is g?
delete[] p; // smart pointer plx
return &ret;
}
How about
static inline void myfunction()
{
static std::unique_ptr<Foo> foo1(Foo::MyFooInitializer(10));
int y = somevalue();
int x = foo1->someFooFunction(int y);
}
If you absolutely need to create the foo1 dynamically, then write an extra class and make it static/global by value. Then use it's destructor to delete object(s).
class MasterControlClass
{
public:
Foo* foo1;
MasterControl(){foo1 = NULL;}
~MasterControl(){delete(foo1), foo1 = NULL;}
};
static inline void myfunction()
{
static MasterControlClass mcp;
mcp.foo1 = Foo::MyFooInitializer(10);
}
In this way, when your program is closing, the mcp desctructor will get called and will do the cleanup.
If you want to reinitialize, then ofc you have to delete foo1 at every assign, just add
if(mcp.foo1)
{
delete mcp.foo1;
mcp.foo1= NULL;
}
Or even better, move it to a method of mcp.