When I run the following code, I get an error.
void printData(int total_trees,int burned){
printf("Before printing data\n");
float percentBurned = (float)burned / (total_trees burned)*100;
printf("total burned: %d (%.1f\%)\n",burned,percentBurned);
printf("trees left: %d\n", total_trees);
// printf("trees left: %d\n", total_trees);
printf("After printing data");
}
The error says *** stack smashing detected ***: terminated
Before outputting the error, it outputs the first three printf statements.
Link to image because this is my first stackoverflow post
I've tried rearranging everything so many times and nothing has worked so far. I'm guessing the printf statements themselves aren't triggering an overflow, but I could be wrong.
I'm grateful for any help you can give :)
edit: printf("trees left: %d\n", total_trees);
is the last line that runs before throwing the error
CodePudding user response:
The correct way to escape a %
character in a format string is %%
, not \%
. A decent compiler should warn you about this if you enable warnings (e.g. gcc -Wall
), which you should always always do.
With that fixed, the program runs correctly for me, with all warnings and sanitizers that I tried (try on godbolt). If it still fails for you, then you need to post a minimal reproducible example, as the bug may be in some other part of your code.