user1014366 user1014366 - 1 year ago 50
C++ Question

Does allocating function scope member causes memory leak?

I used to allocate function scope static members , as it serves very well when the calls to these function(s) are limited to debug purposes and memory is very limited.
I tested the next c++ code:

#include <stdio.h>

class myClass
myClass(int index) : m_index(index)
printf("Constructing element %d\n", m_index);

printf("Destructing element %d\n", m_index);
int m_index;

void foo()
static myClass class1(1);
static myClass *class2 = new myClass(2);


void main()


The printout is

Constructing element 1
Constructing element 2
Destructing element 1
Press any key to continue . . .

Have I caused any memory leak ?
Where does element 1 allocated ?
Where does element 2 allocated ?

Answer Source

That depends on how "memory leak" is defined. Some define it to mean that you allocate memory and then don't deallocate it. In that case, yes, your program has a memory leak since class2 is never deleted. Others define it to mean that you allocate memory and then can't deallocate it because the last remaining pointer to the memory is overwritten or goes out of scope. In that case, your program does not have a memory leak.

Whether your code is "bad" is a matter of opinion. I advise against using explicit new wherever a smart pointer can be used instead. However, some recommend this use of static pointers in order to deliberately prevent the object from being destroyed, in order to avoid bugs that would otherwise occur if a static object is accessed after the end of its lifetime (i.e., during the destructor of another static object, or the invocation of a function registered by atexit).