Stack Overflow Problem

This blog is to give hints on addressing Stack overflow problem on different platforms.
Under Unix-like systems, programs may throw 'Segmentation fault' error. This can be due to stack overflow, especially from recursive function calls or huge data sets. 

Now, how to change the default stack size on different platforms:

  • In general under Unix-like platfrom, the stack size is controlleed by environment variable, not the program itself. So you cannot pass any flags to the compilers, like gcc to setup the stack size. 
  • Under Windows platform, the stack size inforamtion is contained in the executable file. It can be set during compilation time in Visual C++, but this is not available in gcc. Alternatively, Microsoft provides a program  "editbin.exe" which can change the executable files directy. Here are more details:


SunOS/Solaris:  
> limit                                                #shows the current stack size
> unlimit                                           #changes the stack size to unlimited        
> setenv STACKSIZE 32768          #limits the stack size to 32M bytes


Linux:      
> ulimit -a                                         #shows the current stack size        
> ulimit -s 32768                              #sets the stack size to 32M



Windows : 
(During compilation):============================= 
1. Select "Project -> Setting". 
2. Select "Link" page. 
3. Select "Category" to "Output". 
4. Type your preferred stack size in "Reserve:" field under "Stack allocations". eg, 32768 in decimal or 0x20000 in hexadecimal.


(to modify the executable file):=======================================
There are two programs included in Microsoft Visual Studio, "dumpbin.exe" and "editbin.exe". 

  • Run "dumpbin /headers executable_file", and you can seethe "size of stack reserve" information in "optional header values". 
  • Run"editbin /STACK:size" to change the default stack size.

No comments:

Post a Comment