I’m allocating a block of memory in C# to retrieve information from an unmanaged data buffer:
handle = Marshal.AllocHGlobal(33455);
The maximum size of the information retrieved is 33,455 bytes, but the size of the information may be smaller than that in some cases.
How can I determine how many bytes are actually being used in the allocated block, rather than how many are actually allocated?
How is the system supposed to know what data is used vs random? It doesn’t know anything about the structure of your data. All it knows is how much you allocated. You’re not storing bytes in the handle. The handle just refers to a chunk of memory that has been set aside for you.
You could initialize the data to a sentinel value (such as 0xcdcdcdcd which Windows will do in debug mode) and then you can calculate it. Or, if the data is a string, you can call strlen() (or one of the safe string functions). Or you can write some wrapper functions that wrap the APIs you use to write to the memory and keep track of how much data you use.