How to allocate a separate stack for a function manually in C++?

112 views Asked by At

I am trying to allocate a new stack on the heap in C++ for a function using VirtualAlloc. While debugging, I noticed that the rsp value for my function can either increase or decrease relative to the rsp value that goes into the function. But below the memory allocated via VirtualAlloc is NO_ACCESS protected memory, which means that if I set the rsp value to the address returned by VirtualAlloc, a crash will occur because the function will try to access memory it doesn't have access to. I don't think it's safe to write an address like "allocated_address + (allocated_size / 2)" to the rsp, so I need a safer way to allocate memory for the local stack.

I tried allocating memory with _malloca, and below the address this function returns is memory with the same protection attributes as the returned address. But then I don't understand how safe it is, and what does _malloca return, "stack top address" or "base address", and if it is the base address, how can I get a stack top address that I can set in rsp? allocated_address + (allocated_size - 1)?

0

There are 0 answers