Help needed: Memory leak in my C++ application

💻 Coding 105 views 2 replies
I'm experiencing memory leaks in my C++ application. I've been using Valgrind but still can't pinpoint the exact issue.

The leak seems to occur when I'm handling dynamic arrays. Here's a simplified version of my code:

vector<int>* data = new vector<int>();

Am I missing something obvious?

Replies (2)

The issue is that you're creating a pointer to a vector but never deleting it.

Instead of:
vector<int>* data = new vector<int>();

Just use:
vector<int> data;

No need for dynamic allocation here. Vectors manage memory automatically!
Also, if you must use pointers, consider smart pointers like unique_ptr or shared_ptr. They handle cleanup automatically:

auto data = make_unique<vector<int>>();

This way you don't have to remember to call delete!
Please login or register to post a reply.