Debugging memory corruption

I used to run into a dynamic memory issue in C (visual studio). I had a more or less working program that ran a runtime error when freeing one of the buffers. This was a clear memory corruption, the program wrote at the end of the buffer.

My problem is time consuming. The error was reset down after the corruption, and I had to manually debug the entire run to find when the end of the buffer was being rewritten.

Is there any tool \ way to help fix this problem? if the program crashed immediately, I would have found the problem much faster ...

problem example:

int *pNum = malloc(10 * sizeof(int)); // || // \/ for(int i = 0; i < 13; i++) { pNum[i] = 3; } // error.... free(pNum); 
+6
source share
4 answers

I am using pageheap . This is a tool from Microsoft that modifies the operation of the dispenser. When you go to the page, when you call malloc, the distribution is rounded to the nearest page (memory block), and after it is placed an additional page of virtual memory that is configured to have no read / no write. The selected dynamic memory is aligned so that the end of your buffer is directly in front of the end of the page in front of the virtual page. Thus, if you go over the edge of your buffer, often with a single byte, the debugger can easily catch it.

+3
source

I use "data breakpoints" for this. In your case, when the program crashes, it may first file a complaint as follows:

Heap block at 00397848 changed to 0039789C with requested size 4c

Then run your program again and set the data breakpoint at 0039789C . When the code writes to this address, execution stops. It often happens that I found an error right at that moment.

If your program allocates and frees memory again, and it turns out that it is at this exact address that you simply disable deallocation:

 _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_DELAY_FREE_MEM_DF); 
+3
source

Is there any tool \ way to help fix this problem?

Yes, this is exactly the type of error that static code analyzers are trying to find. e.g. splint / PC-Lint

Here is a list of such tools: http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis

Edit: When testing a piece of code, you will receive the following warning:

main.c: 9: 2: It is possible to save beyond the borders: pnum [i]

Presumably this warning would help you.

+2
source

Our CheckPointer tool will help you find memory management errors. It works with the dialogs of GCC 3/4 and Microsoft in C.

Many dynamic checkers only capture access outside the object, and then only if the object is selected in a heap. CheckPointer will detect memory access errors inside the object allocated by the heap; illegally gain access to the end of a field in a structure regardless of the type of field; most dynamic checkers cannot detect such errors. He will also find access to the edge of local residents.

0
source

Source: https://habr.com/ru/post/917716/


All Articles