When does the stack really overflow?

后端 未结 6 1534
别跟我提以往
别跟我提以往 2020-12-17 05:35

Is infinite recursion the only case or can it happen for other reasons? Doesn\'t the stack size grow as needed same as heap?

Sorry if this question has been asked be

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 05:43

    On a laptop or desktop machine it may be unusual to overflow the stack without infinite (or very deeply nested) recursion when running from the main thread... however, stack overflows are not uncommon for:

    • Threaded code in which the thread has been allotted a small, fixed-sized stack.
    • Signal handling code in which the signal handling context has a small, fixed-sized stack.
    • Code executing on embedded devices, where memory is generally scarce.

    As an example, if you register a signal handler using sigaction, if the signal handler does any complex (i.e. deeply nested operations) it is very easy to get a stack overflow on a number of operating systems, since signal handlers are usually allotted a small, fixed-sized stack. Similarly, if you spawn a thread with pthread_create, but you specify a small stacksize with pthread_attr_setstacksize, then it is very easy to attain a stack overflow. On very memory-limited devices such wireless sensors, it is an art to avoid stack overflows.

提交回复
热议问题