I’m writing a C# library where the calling app will pass in a large amount of contiguous, unmanaged memory. This calling app can be either from .Net or Visual C++ (it will go through an intermediate C++/CLI library before calling my library if from C++). It would be useful to validate that there is sufficient memory, so I decided to call the _msize() function. Unfortunately, _msize always seems to give me the wrong size back.
I went back and modified my allocation routine in my sample app and then immediately call _msize. Here is my code snipet:
public unsafe class MyMemory
{
/// <returns></returns>
[DllImport("msvcrt.dll", SetLastError = true)]
public static extern int _msize(IntPtr handle);
public static IntPtr MyAlloc(int size)
{
IntPtr retVal = Marshal.AllocHGlobal(size);
...
int memSize = MyMemory._msize(retVal);
if (memSize < size)
{
...
}
return retVal;
}
When I pass in the size 199229440, I get back memSize of 199178885. I’ve seen similar results for different numbers. It is less than 0.01% off, which I would totally understand if it was over, but the fact is it is under, meaning _msize thinks the allocated memory is less than what was asked for. Anyone have any clue why this is? And any recommendations on what I should do instead would be appreciated as well.
P/Invoke the
LocalSizefunction instead._msizeis for determining the size of a block allocated withmalloc(and its friends).AllocHGlobalis a wrapper aroundGlobalAllocorLocalAlloc(depending on what reference you believe; but I think the two are equivalent), and you want theLocalSizefunction to determine the size of the block that actually returned. So far as I can tell,Marshaldoesn’t contain a wrapper forLocalSize, but you can call it using P/Invoke.So it seems like it’s only by sheer good luck that
_msizeis returning anything useful for you at all. PerhapsmallocusesGlobalAlloc(orLocalAlloc), either always or just when asked for large blocks, and requests a bit of extra space for bookkeeping; in which case_msizewould be trying to compensate for that.