Today, when running a function in a company's project, a strange segment error occurs.
At first, I thought which string was inconsistent in the sprintf type or a pointer encountered a problem. After searching for the result for a long time, I did not find this problem. I also used GDB for tracking, the result is traced to a segment error. The BT command is used to list the current function stack list. The error is found to be another function in the library file developed by someone else. No source code is available, in this case, there are only two solutions:
(1) Find the source code and view the source code;
(2) comment out the code around the function that is near a segment error;
Because the company is difficult to find the code, and the code in this database is not fully understood at half past one, the second solution is adopted.
This problem still exists after the second method is used for annotation, finally, I tried to change a 800-byte char array in this function to 200 bytes (because only 190 bytes are used through GDB debugging), and then compile and run it, this is enough. If we change the size to 400 bytes, there will be another segment error, so we guess there should be a limit on the size of the stack space of a program, finally, I tried to use malloc to allocate 800 bytes of space on the heap, and there was no problem after compilation and running. Finally, I thought it was caused by insufficient stack space.
The maximum stack size supported by a process in the test system I wrote is as follows:
/************************************
* Author: Samson. Wen
* Create Date: 2011-02-14
* Info: Maximum byte value of the Linux program stack.
***********************************/
# Include <stdio. h>
Int testtack (INT num)
{
Int buff [num];
Printf ("num is % d/N", num );
Return 0;
}
Int main (INT argc, char * argv [])
{
Int buflen = 2*1024*1024;
For (; buflen <8*1024*1024; buflen ++)
Testtack (buflen );
Printf ("Hello, world ");
Return 0;
}
My current running results are as follows:
......... N pieces of print are omitted
Num is 3143036
Num is 3143037
Num is 3143038
Num is 3143039
Num is 3143040
Segment Error
The value displayed before a segment error is the maximum stack size supported by the current process. The value is 3143040 int values, that is, 3143040*4 bytes.