stackalloc allocates memory for an array on a stack, but it has severe restrictions; in particular, you cannot free memory before exiting the method, you cannot declare a pointer to an array as a class field, you cannot pass a pointer to an array into method parameters.

Question: Is there another way to allocate memory for an array on the stack, transfer it to the method parameters, declare it to be a class field?

ps even an experimental version will do; I saw, for example, that even classes could be initialized on the stack by changing the platform itself.

  • one
    Well, you allocated memory on the stack, assigned an address to the field of the class, left the method - the stack went away. What does the field indicate? - Alexander Petrov
  • You may need a fixed buffer. - Alexander Petrov
  • And why do you need stackalloc, let me ask? - VladD
  • @VladD, why did the developers add stakolok in the ball? To allocate memory on the stack, not in the heap. - Align
  • one
    @VladD, in the production code, someone is unlikely to use this, otherwise there is a risk of having a strong headache in the future. The behavior of future versions of CLR and JIT is not predictable. But as a self-education and sports interest - quite an interesting topic. - Align

1 answer 1

I think it’s impossible at the language level.

The fact is that C # is a safe language. Unlike languages ​​like C and C ++, in which you can do anything and get dangling pointers, C # will not let you do this. (The result of this is, for example, the impossibility of stack disruption attacks on .NET applications.)

If it were possible to allocate memory on a stack, and memorize a pointer to it in a class field, then this object could survive the stack frame to which it refers, and you would get access to someone else's memory. Such a secure language is not allowed.

OK, you can bypass the limitations of the language, and turn it into C using an unsafe context. In unsafe-context, you can still paste the pointer into IntPtr and save it to the class in this form.

 class UnsafeContainer { public IntPtr data; } class Program { static UnsafeContainer container; static unsafe void Main(string[] args) { int* addr = stackalloc int[100]; container = new UnsafeContainer { data = (IntPtr)addr }; } } 

With this coding, you lose all the benefits of a safe language, and acquire the same undefined behavior as in C ++. I hope that you really need it very much . At the slightest error in unsafe code, expect problems in completely unrelated places, as is usually the case with UB.

  • Thank you, all ingenious is simple. It never occurred to me to use IntPtr. I repeat - the code is only for sports interest. - Align
  • @Align: I remember, the last paragraph of the answer is more likely for future readers. - VladD
  • @Align: Please, glad that helped. - VladD