Search code examples
c#stackalloc

How to read the element count of stack allocated memory?


Let's say I have just a pointer of previously stack allocated memory and I would like to know how many elements I have. How to do it?

MSDN says: "the use of stackalloc automatically enables buffer overrun detection features in the common language runtime" so I guess the size is kept somewhere.


Solution

  • The information you're looking for doesn't exist, it's your responsibility to keep track of this.

    The buffer overrun detection doesn't check for out-of-bounds access on the "array" - there is no array. Instead, it uses a random value added after the allocated memory on the stack. In the function epilog, it checks if the value is still there - and if not, kills the whole process.

    Buffer overflow protection for stackalloc in .Net

    Needless to say, this doesn't make it certain you don't suffer from a buffer overflow (or underflow, which is the main concern here). It just tries to limit its potential impact. In combination with keeping stackallocced locals in as small functions as possible, this serves as a pretty simple, while still quite effective, prevention of malicious code execution. You can still overwrite (or read) other locals, but you can't overwrite e.g. the function return pointer.