Hi,
I don't understand why when b is created on the stack. It would cause memory leaks.Code:void A::A()
{
B *b = new B;
b->Setup(....);
}
I commented that part out, the leaks were gone. Any thoughts?
Thanks
Jack
Printable View
Hi,
I don't understand why when b is created on the stack. It would cause memory leaks.Code:void A::A()
{
B *b = new B;
b->Setup(....);
}
I commented that part out, the leaks were gone. Any thoughts?
Thanks
Jack
There's a simple rule to avoiding memory leaks:
For every new, delete.
For every new[], delete[].
For every malloc(), free().
Things aren't always that simple, of course, but here they are----you've allocated a B on the heap, stored its address only in a local pointer (so far as you've shown us), and not cleaned it up anywhere. Textbook memory leak.
B is not created on the stack , it is on the heap cause *b is getting its address from new keyword , so there you have it , as Lindley pointed out just follow these simple rules you'be all right.
Exactly as monarch and lindley says ... It is no different to normal c or c++ code
void funcA(void){
void* b;
b = malloc(256);
// do nothing or do whatever you want with b
// if you dont do free(b);
// you will bleed in my case 256 bytes of memory
}
New and malloc do the same sort of thing they allocate memory, free and delete release allocated memory
The answer is to not use bare pointers unless you have to or they are just observers. Any time ownership is concerned you should use a smart pointer such as boosts shared_ptr or std::shared_ptr if your compiler supports it. Then when the smart pointer goes out of scope the memory will be automatically reclaimed by the smart pointers destructor ( or at least its reference count will be decremented and when that hits zero the object will be deleted ). Read up on the principle of 'Resource Acquisition Is Initialisation (RAII)' and smart pointers.
---
If you instead of this
B *b = new B;
think of it like this (which is logically equivalent),
B *b;
b = new B;
the situation becomes clearer. The first line declares a pointer variable b of type B to be allocated on the stack. The second line allocates a B type object on the heap and assigns its pointer to b. It's only the allocation of the B object on the heap that can cause a leak. To prevent it you must put in this line when the object isn't used anymore.
delete b;
Some languages with built-in automatic garbage collection, such as Java and C#, will handle the deletion automatically but not C++. In C++ every new must have a matching delete (and every new[] a delete[]) or you have a memory leak on your hands.
When ever it becomes hard to determine when and where an object is to be deleted it's time to consider putting a so called reference counting "smart" pointer in charge of the situation. It will delete the object when it's no longer pointed to from anywhere anymore and thus can be safely deleted.