When do you worry about stack size?

前端 未结 19 1167
难免孤独
难免孤独 2020-12-10 12:41

When you are programming in a language that allows you to use automatic allocation for very large objects, when and how do you worry about stack size? Are there any rules o

19条回答
  •  时光取名叫无心
    2020-12-10 13:28

    You start to worry about stack size when:

    • when your program crashes - usually these bugs tend to be weird first time you see them :)
    • you are running an algorithm that uses recursion and has user input as one of its parameters (you don't know how much stack your algorithm could use)
    • you are running on embedded platforms (or platforms where each resource is important). Usually on these platforms stack is allocated before process is created - so a good estimation about stack requirements must be made
    • you are creating objects on the stack depending on some parameters modifiable by user input (see the sample below)
    • when the code executed in a thread/process/task is very big and there are a lot of function calls that go deep into the stack and generate a huge call-stack. This usually happens in big frameworks that combine a lot of triggers and event processing (a GUI framework; for example: receive_click-> find_clicked_window-> send_msg_to_window-> process_message-> process_click-> is_inside_region-> trigger_drawing-> write_to_file-> ... ). To put it short, you should worry about call-stack in case of complex code or unknown/binary 3rd party modules.

    sample for modifiable input parameters:

    in my_func(size_t input_param)
    {
      char buffer[input_param];
      // or any other initialization of a big object on the stack
      ....
    }
    

    An advice:

    • you should mark the stack with some magic numbers (in case you allocate it) and check if those magic numbers will be modified (in that case the stack will not be enough for the task/thread/process and should probably be increased)

提交回复
热议问题