<>c++ Memory Pointer out of bounds detection mechanism _CrtMemBlockHeader

c++ Of new and delete operation , Can let us in the program run the dynamic development of memory space , But we know , Once not handled properly, it will cause memory leakage . There has always been a question ,c++ To prevent ( Or testing ) What did the pointer do when it crossed the boundary ?

<>struct _CrtMemBlockHeader

_CrtMemBlockHeader : This structure , It stores all kinds of information of memory block obtained from dynamic application , And back to your pointer . The details are as follows :
typedef struct _CrtMemBlockHeader {   // Pointer to the next block of data   struct
_CrtMemBlockHeader*pBlockHeaderNext; // Pointer to the previous block of data struct _CrtMemBlockHeader *
pBlockHeaderPrev; // File name: The path and name of the file where the line of code requesting the memory allocation operation is located , But it's actually a null pointer char *
szFileName; // Line number: Line number , The line number of the line of code that requests the memory allocation operation int nLine; // The size of the request allocation size_t
nDataSize; // Type of block type int nBlockUse; // Request number long lRequest; //
this gap, Exactly cpp Bounds for pointers in unsigned char gap[nNoMansLandSize]; } _CrtMemBlockHeader;
Let's talk about it gap[] The role of , The content of the space you applied for is assumed to be <tdata>. stay <tdata> Before and after 4 individual B( byte ) Of gap[], Its value in memory is 0xFD
. So the system only needs to detect your <tdata> Whether the data before and after is 0xFD You'll know if you've crossed the line .

In the actual test , We applied to create one int Type p Pointer , Change the display of memory to 4 column 16 System ( The following pictures are from vs2019 Of debug pattern )

We can see that ,0x00FC05A0 It's ours p What the pointer points to , Because we didn't create the content, we used it in memory 0xcd Fill in , Before and after 4B Of 0xfd To limit .

<> How to detect memory leaks

We know from above gap[] And his role , Then we will think of it successfully _CrtDumpMemoryLeaks() This function , He just checks the memory allocation list (
pBlockHeaderNext and pBlockHeaderPrev Double chain of double linked list ), To find out if there is a leak .

©2019-2020 Toolsou All rights reserved,
Send love - A little romance for programmers VHDL—— Design of frequency divider Python Implementation of Hanoi Tower code It's over , Starting salary 30khtml+css+js Make a simple website home page QQ Login interface implementation Hill sorting of sorting algorithm ——c++ realization 【 Wechat applet learning 】 Netease music cloud code page implementation details Resume the 13th session python Blue Bridge Cup 2022 Solution to the 13th Blue Bridge Cup ( whole )