Reputation:
class MyClass
{
// empty class with no base class
};
int main()
{
MyClass* myClass = new MyClass();
return 0;
}
Is this a memory leak?
Upvotes: 3
Views: 241
Reputation: 138031
Yes. Even though your class is empty, you still leak memory. There are a few reasons for this:
char
).So, your code leaks at least one byte of memory, plus the allocation details, even if your struct is empty.
Upvotes: 8
Reputation: 25551
Note that everything is guaranteed to be at least the size of a C++ byte, which is always the same size as a char
. (Your mileage may vary on exotic systems, but this is generally eight bits. Check with CHAR_BIT
.) So, yes, it will take up memory (albeit very little) and that memory will be leaked.
Therefore, not deleting an object will, indeed, always leak memory.
Upvotes: 1
Reputation: 354969
You have a memory leak any time that:
at this point, you are incapable of destroying the dynamically allocated object and thus the object is leaked.
In your example program, you dynamically allocate a MyClass
object and set myClass
to point to it. myClass
is the only pointer to the dynamically allocated object. You then return from the function and lose the pointer; at this point, the dynamically allocated MyClass
object is leaked.
Whether or not this matters depends on what the object is, what the program is, and when the leak occurs. If the object doesn't need to do any cleanup when it is destroyed (e.g., if its destructor is trivial), then failing to destroy it before the program terminates is usually bad style but is not particularly bad, relative to other sorts of leaks.
Upvotes: 7