1. Problem Phenomenon
The code that runs normally on CentOS 7 crashes when compiled and run on CentOS 8.
2. Troubleshooting Process
The crash occurred at a location in the test case that should not have been reached, so I first commented out that part of the code. It then crashed again after reaching the next function body, so I used gdb to debug the execution. Using disassemble, I found that a function executed without returning to other function bodies. Upon reviewing the code, I discovered that a function declared to return an int value did not have a return statement. Adding return 0; resolved the issue. I then wrote a small demo to analyze the generated instructions in detail.
3. Example Explanation
The code I wrote is as follows. When optimizations are not enabled, it runs normally in both environments, so I will use O1 optimization as an example to look at the generated instructions:
First, on g++ 6.3 (CentOS 7), the generated code is as follows. You can see that there is a ret instruction:
Next, let’s look at the code generated in the g++ 8.3.1 (CentOS 8) environment. You can see that there is no ret instruction, and it continues to execute into other function bodies.
Finally, let’s look at the code generated when a void return type function does not include a return statement. You can see that it does not require a return statement and still adds such an instruction automatically.
4. Prevention Methods
You can enforce coding standards or enable -Werror to turn warnings into errors.