Is there a memory leak in this small program?

Sorry for asking so many pointer questions.. My last one though...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
class Box {
public:
    int x, y;
};

Box* eenNieuweBox() {
    Box b;
    b.x = 5;
    return &b;
}

int main() {
    Box* b;
    
    b = eenNieuweBox();
    cout<<b->x;
    return 0;
}


I assume if you don't use the new keyword, you don't have to delete it right? So this program is good?
There isn't any memory leaks because no free store memory is allocating using new.

However, there is a huge problem with eenNieuweBox(). Box b is created on the stack of the eenNieuweBox() function call, which means b will be destroyed when the function returns. By returning a pointer to b, the function is returning a pointer to a destroyed object. Instead, return b by value.
1
2
3
4
5
Box eenNieuweBox() {
    Box b;
    b.x = 5;
    return b;
}


Never put user defined anyting in the std namespace.
Your program will crash exhibit undefined behaviour. Box b is created on the stack in your eenNieuweBox() function. When the function returns, b falls out of scope and the box is destroyed. In main, your pointer b will be pointing to memory that is no longer valid.
The program has undefined behaviour because you are returning a pointer to a local variable from a function. This local variable will be destroyed or can be overwritten by something else so the pointer will be invalid.
So there is no memory leak but there is undefined behaviour.
Last edited on
Thank you.
Topic archived. No new replies allowed.