// --------------------------------------------------------------- // File: Check_Memory_Demo.cpp // Purpose: Demonstrate how to: // - Access Debug heap's state // - Have the DCRT check memory functionality // to track memory leakks & overwrites. // Author: Divyanand Kutagulla, dkutagulla@hotmail.com // Source: Run-time library reference VS.NET 2003 help system // Course: Software Testing Seminar, Spring 2004 // --------------------------------------------------------------- // 1 --------------------------------------------------------- // Define _CRTDBG_MAP_ALLOC symbol before everything. // This Symbol MUST be the first line in the file so that // first during preprocessing even before any header files // (specified in the include directives) are processed. // This define sets up the mapping of the // memory allocation and deallocation routines (malloc/new/ // free/delete) to the special debug versions that record // the file name and line number within the file where the // memory request was made #define _CRTDBG_MAP_ALLOC //--------------------------------------------------------- // 2 ------------------------------------------------------ // all the include files that we want to include go here // after the _CRTDBG_MAP_ALLOC has been #defined above #include "..\Common\myclass.h" #include "..\Common\dcrt_setup.h" #include //------------------------------------------------------ // 3 ----------------------------------------------------- // finally include the Debug C runtime header #include //----------------------------------------------------- #include // crt_set_security_error_handler.c // compile with: /GS #include #include #include void __cdecl report_failure(int code, void * unused) { if(code == _SECERR_BUFFER_OVERRUN) printf("Buffer overrun detected! Program will end.\n"); exit(1); } void vulnerable(const char *str) { char buffer[10]; strcpy(buffer, str); // overrun buffer !!! } void uninit_locals() { int i; //int i is uninitializecd and will be set to OxCCCC //by compiler when the /RTCu is set... int j =i; //throw an exception during program execution } void truncate() { int i = 0xFFFF; char c = (i & 0xFF); //correct way to initialize a char from an int without truncation //truncation is happening here.. when /RTCc is set up, //a runtime error will be thrown when both these staments are executed... char w0 = (char)i; char w1 = i; } int main() { char large_buffer[] = "This string is longer than 10 characters!!!"; //produce uninitialized local variable runtime failure uninit_locals(); //produce Datavalue truncation error truncate(); #ifdef CUSTOM_BUFFER_OVERRUN_HANLDER _set_security_error_handler(report_failure); #endif vulnerable(large_buffer); }