Recently, I found a Bug in my project and killed the process. I checked it and found it was the most inconspicuous place. I will record it here.
First look at the following code
# Include <iostream> # include <stdio. h> using namespace std; int main () {char aa [1024] = {0}; float f = 50.123456; // the intention is to output a floating point number to a string, the number of decimal places is two. sprintf (aa, "% 0. * f ", f); printf (" % f \ n ", f); cout <aa <endl; sprintf (aa," % 0. * f ", 2, f); cout <aa <endl; cout <" Hello world! "<Endl; return 0 ;}
The running result is as follows:
In the code, sprintf (aa, "% 0. * f ", f); you want to output a floating point number to a string and control the number of digits after the decimal point. However, if you do not specify the number of decimal places, as a result, sprintf prints a long string of data to the variable aa. When the space of aa is insufficient, the array will be out of bounds, resulting in program crash. This is the reason for the process being killed in the project. As for how the sprintf function prints such a long string of data, wait for the source code to be analyzed.