came in to develop C + + projects under Linux and encountered a very strange bug. The project requires a multi-threaded implementation, and when the code is written, it will prompt for a segment error (segmentation fault) whenever other functions such as printf, fopen, etc. are called inside the thread function. Programming for a long time, consciously do not appear very low-level grammatical errors, after careful examination did not find any problems. After reading the code to a lot of bad friends did not help to find this bug, and then after their own thinking finally found the problem. The following first gives the simplified framework of the thread function:
void* Thread_func (void* rank) { long My_rank = (long) rank; printf ("Thread%ld is working...\n", My_rank); //... Char BUFFER[BUFF_SZ]; //...}
This code compilation must pass, the runtime at the variable assignment is not a problem, but when running to the printf call function will be a segment error, which means that the function address is not found, but why this problem?!
Originally, pay attention to the buffer array definition that row, inside the array size is a custom global constant, this constant because the business requirements are determined to be larger (around 50MB), this is the crux of the problem! This array definition occupies the thread stack memory, but the Linux thread occupies a stack memory limit of 8MB, so that buffer actually fills the entire thread stack memory, which causes the function entry to be found inside the runtime thread. So in this case, mark, if someone encounters a similar problem later, I hope to consider this point.
In general, this is a simple problem to solve, but it's really hard to find (it takes 3 days). )。 There are two main reasons: 1. We seldom apply for very large stack memory before, so although we can understand the principle of stack memory limit, there are few actual mistakes; 2. The array size is expressed as a constant (the enterprise will have this requirement to avoid magic number), it is difficult to find that this is too large. So when it comes to this kind of problem, it's really possible to waste a lot of time without experiencing it. I hope this article will help meet similar bugs in the future, less detours, less time spent.
At last:
solution : Use new to dynamically allocate memory to open up heap memory space, but finally remember that delete is released.
How to find the bug : First, the function body all comments, and then follow the program section to run the comment, to see which of the added program segments caused by the problem.
Linux C + + inexplicable Magic segment Error (segmentation fault), unable to invoke other functions