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

前端 未结 12 1532
遇见更好的自我
遇见更好的自我 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:23

    There isn't a nice way I can think of. Maybe it is possible by using getrlimit() (suggested before) and some pointer arithmetic? But first ask yourself if you really want this.

    void *closeToBase;
    
    main () {
      int closeToBase;
      stackTop = &closeToBase;
    }
    
    int stackHasRoomFor(int bytes) {
      int currentTop;
      return getrlimit(...) - (¤tTop  - closeToBase) > bytes + SomeExtra;
    }
    

    Personally, I'd not do this. Allocate big things on the heap, the stack was not meant for it.

提交回复
热议问题