Accessing stack that is allocated to the thread
i want to know whether if its possble to access the stack(allocated to the thread which is used to store local variables etc.) c开发者_JAVA百科ontent progarmitically .this can help in my effort to programatically determine stack overflow issues.thanks in advance
Not portably, no. However, depending on the platform you're using you may be able to set the stack size for each thread. For example, if you're using POSIX threads, you can use pthread_attr_setstacksize to set the stack size.
On Unix, you can setup an alternate signal stack and use this to detect stack overflow (after you bomb). When your thread hits overflows the stack (assuming you or the OS puts a guard page there), you can look at the stack register in the sigcontext_t to see if that's why.
If you are looking to prevent the stack overflow programmatically, allocate your own thread stack, and then sample the stack pointer value periodically (you'll have to deal with unportable issues of where your stack base is located, and how to sample the stack pointer). For a single threaded program, you can use the stack base as sampled in main, compared to the process stack ulimit to see if you are getting too far.
This is all non-portable, but possible.
There is no portable way. You can use inline assembler to determine current stack pointer within thread, and then locate block with this address within process memory map.
But usually stack overflow issues determined by operating system. When stack is allocated for thread or process there is special memory segment placed before it, with read and write to this segment disabled. When you run out of stack, your application reaches this segment and accessing it will cause system exception.
精彩评论