Is it possible to predict a stack overflow in C on Linux?

前端 未结 12 1530
遇见更好的自我
遇见更好的自我 2021-01-13 14:44

There are certain conditions that can cause stack overflows on an x86 Linux system:

  • struct my_big_object[HUGE_NUMBER] on the stack. Walking throu
12条回答
  •  迷失自我
    2021-01-13 15:41

    You can determine the stack space the process has available by finding the size of a process' stack space and then subtracting the amount used.

    ulimit -s
    

    shows the stack size on a linux system. For a programmatic approach, check out getrlimit(). Then, to determine the current stack depth, subtract a pointer to the top of the stack from one to the bottom. For example (code untested):

    unsigned char *bottom_of_stack_ptr;
    
    void call_function(int argc, char *argv) {
        unsigned char top_of_stack;
        unsigned int depth = (&top_of_stack > bottom_of_stack_ptr) ? 
            &top_of_stack-bottom_of_stack_ptr : 
            bottom_of_stack_ptr-&top_of_stack;
    
        if( depth+100 < PROGRAMMATICALLY_DETERMINED_STACK_SIZE ) {
            ...
        }
    }
    
    int main(int argc, char *argv) {
        unsigned char bottom_of_stack;
        bottom_of_stack_ptr = &bottom_of_stack;
        my_function();
        return 0;
    }
    

提交回复
热议问题