SQLite Forum

Odd buffer overflow
Login
Expanding on what \_msize_dbg() is documented or supposed to do:

The difference between what \_msize_dbg(...) returns (as documented) and what \_msize(...) returns is (sizeof(\_CrtMemBlockHeader) + nNoMansLandSize). This can be seen at [CRT Debug Heap Details](https://docs.microsoft.com/en-us/visualstudio/debugger/crt-debug-heap-details?view=vs-2019), remarks under "**Find buffer overruns with debug heap**" and in the next code block.

With that adjustment for debug builds (using the MSCRT debug heap), \_msize() could be made to return what one might suppose it should under the assumption that debug instrumentation should not change the API function.  A suitably placed re-#define would do it:

```
#undef _msize
#define _msize(p) (_msize_dbg(p) - sizeof(_CrtMemBlockHeader) - nNoMansLandSize)
```

Ugly, yes. Worse than avoiding code that uses \_msize(), arguably not.

Once the contract putatively enforced by those guard bytes is considered, it as arguably required to use realloc() to do what is done with the combination of an \_msize() call and then writing beyond the earlier requested allocation. After all, realloc is supposed to be smart enough to leave the block in place if there is room at its end.