简体   繁体   中英

Proper way to check for memory leaks in Visual C++

I've been trying to improve my own personal C++ skills lately, so I implemented an Array List as a learning exercise. After I got it working, I started checking for memory leaks, and became very confused by the output.

Source on GitHub (main.cpp, ArrayList.cpp, ArrayList.h)

I got a lot of information about how to start checking for leaks from this page from Microsoft (hence the declarations at the top of the main file, the start of the main function, and the top of the ArrayList.cpp file.

Visual Studio is telling me this information:

Detected memory leaks!
Dumping objects ->
c:\users\cody\desktop\arraylist\arraylist\arraylist.cpp(48) : {4267} normal block at 0x007F9BC8, 3992 bytes long.
 Data: <                > 00 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 
Object dump complete.
The program '[16620] ArrayList.exe' has exited with code -1073741510 (0xc000013a).

And the section of code in question

void AL::ShrinkToFit()
{
    int* newArray = new int[currentIndexOfFirstOpen]; //Line 48, as mentioned in the mem leak output
    for (int i = 0; i < currentIndexOfFirstOpen; i++)
    {
        newArray[i] = currentArray[i];
    }
    int* oldArray = currentArray;
    currentArray = newArray;
    delete[] oldArray;
    currentMaxLoad = currentIndexOfFirstOpen;
}

So clearly I'm missing something. If you check the ArrayList.cpp file linked above, it (under different circumstances) tells me I have a leak anywhere in that file that I have "new int[some number]". The page from Microsoft says that I have to use the preprocessor to redefine new because it only works with the C runtime, but it makes no mention of delete (or delete[]). Is this memory actually being leaked? I have a matching delete[] for every new[], but I can't tell if it is a legitimate leak or if the leak detecting tools just don't understand delete. I tried replacing delete with free (I let the preprocessor redefine new as in the Microsoft article), and it made no change. If I am leaking, can someone point out where/why?

I tried to run your code with Visual Leak Detector ( https://vld.codeplex.com/ ) and it appears you don't have a memory leak, but when exiting (with the close button) the command prompt the leak detector fails and detects a leak in the line you mentioned. Try deleting this line in the main.cpp

Sleep(1000000); //hold the prompt open

and put this instead

std::cin.get();
return 0;

Provide a keystroke at the end of the program and exit with code 0 to the operating system, this should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM