0

I want to ask some of the problems about C++ memory leak. And what is my mistake of my programme and how to rewrite the programme to prevent memory leak. Thank you

int **ptr = new int*[5];
for (int i = 0; i < 5; i++)
  ptr[i] = new int (i+1);
delete ptr;
1
  • 1
    In a toy example like this, it's easy to count the number of new and new[] statements and the number of delete and delete[] statements and see whether they match. You have 1 new[] and 5 news. You have 0 delete[]s and 1 delete. So in this case none of the new[] or new allocations you created are being cleaned up correctly. Commented Mar 31, 2022 at 13:47

1 Answer 1

4

Don't use raw pointers when avoidable. Use std::vector instead.

std::vector<int> ptr(5);
for (int i = 0; i < 5; i++) {
  ptr[i] = i+1;
}

If you are forced to use raw pointers for some reason, delete whatever you allocated. Also note that you have to use delete[] to delete what is allocated via new[].

int **ptr = new int*[5];
for (int i = 0; i < 5; i++)
  ptr[i] = new int (i+1);

for (int i = 0; i < 5; i++)
  delete ptr[i];
delete[] ptr;
Sign up to request clarification or add additional context in comments.

1 Comment

The first code follows a vector logic, the second one corresponds to a matrix logic ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.