Hakon89
Hakon89

Reputation: 1037

C++ CRT Memory Leak

I am having a problem with lots of memory leaks.

CRT shows leaking in the following code for example:

char *cmd = new char[128];

What should I do?

char *cmd = new char[128];
delete[] cmd;

I started new project with VLD (Visual Leak Debugger) with the code above and it still says I am leaking.

Upvotes: 0

Views: 678

Answers (4)

Ghita
Ghita

Reputation: 4505

use:

std::vector<char> cmd(128);

Whenever you need access to the char* buffer you can do:

char* memory = &char[0] as memory is guaranteed to be continue for std::vector. No need to delete because memory is owned by the object. This makes your code also exception safe, e,g, you will not leak memory in case there is an exception thrown before you do the delete []

You can also use the new std::array from C++11 also if you want to allocate on the stack

Upvotes: 0

Paolo Brandoli
Paolo Brandoli

Reputation: 4750

It could be that your objects are deleted after the leak detection runs.

For instance, if you have static objects, you have to pay attention to the deletion order so that their deletion occurs before the leak detection occurs.

Try to embed the new/delete in a function and see if the leaks are still reported: if not, then the problem may indeed be related to the objects being deleted after the leak detection has been executed.

Upvotes: 0

Vite Falcon
Vite Falcon

Reputation: 6645

You should be calling delete[] arrayVariable; and not delete arrayVariable; to avoid memory leaks that are to do with arrays.

Upvotes: 0

ulidtko
ulidtko

Reputation: 15570

Basically, you need to free the memory as soon as you stop using it.

Some good C++ techniques for automating this are RAII and smart pointers.

Also consider Wikipedia article on memory leaks.

Upvotes: 3

Related Questions