I have difficulty understanding this piece of code:
Particularly this part:
// check that the stuff we wrote has not changed
if(n[k][0]!=(unsigned char)(n[k]+s[k]+k))
printf("Error when checking first byte!\n");
if(s[k]>1 && n[k][s[k]-1]!=(unsigned char)(n[k]-s[k]-k))
printf("Error when checking last byte!\n");
The whole program tries to mimic the Windows’ malloc and free function.
It must be run on Windows.
Anyone can explain how those 2 ifs work?
Thanks.
The code makes more sense with a bit more context.
The last two lines set the first and the last byte to values using a formula based on the pointer value (
n[k]), the size of the allocation (s[k]), and the pointer index (k). There is no meaning to this formula, it’s just a calculation of a value to be stored that will be different for different pointer allocations.The
ifstatements you highlighted check that the values of the first (n[k][0]) and last (n[k][s[k]-1]) bytes haven’t changed before freeing the memory. The code is basically a test harness for theVirtualAllocandVirtualFreefunctions.