Listing 1: mem_leak.cpp
Different functions used to detect memory leaks
/****************************************************************************/ /* This program shows the different functions used to detect memory leaks */ /* Author : Sumit Agarwal */ /****************************************************************************/ #include <iostream.h> #include <crtdbg.h> #include <string.h> int main() { _CrtMemState sh1, sh2, sh_diff; _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); char *ptr1 = new char[100]; strcpy(ptr1,"This memory leak was created by Sumit"); cout << ptr1 << endl << endl;; _CrtMemCheckpoint(&sh1); char *ptr2 = new char[10]; strcpy(ptr2,"ABCDEFGHIJKL"); // copying 12 char in string of size 10 _CrtMemCheckpoint(&sh2); cout << "\nOutput of CrtCheckMemory\n" << flush; _CrtCheckMemory(); // shows corrupt memory _CrtMemDifference(&sh_diff, &sh1, &sh2); // calcs. diff. between cp1 and cp2 cout << "\nOutput of CrtMemDumpStatistics\n" << flush; _CrtMemDumpStatistics(&sh_diff); // shows the diff. calculated above cout << "\nOutput of CrtDumpMemoryLeaks\n" << flush; _CrtDumpMemoryLeaks(); // any memory leak at the end of execution ? return 0; } //End of File