4

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

4
  • 5
    Does the error go away if you replace \% with %%? Commented Sep 3, 2022 at 22:54
  • 1
    Stack smashing is not the same as Stack Overflow. Overflow is making a call that requires more stack than is available. Stack smashing is detected writing outside already allocated space. Commented Sep 3, 2022 at 23:34
  • 1
    What makes you think that the line you specified is the last line that runs before the error is thrown? Did you come to this conclusion because "trees left:" is printed, but "After printing data" is not printed? Or did you run the program line by line in a debugger? If it is the former, then your conclusion could be false, because stdout is normally buffered and therefore not necessarily printed immediately. In that case, you may want to consider printing to stderr instead, which is normally unbuffered. Commented Sep 3, 2022 at 23:36
  • Gwendolyn Krezel, Curious why use float percentBurned and not double percentBurned? Commented Sep 4, 2022 at 3:26

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing this out! I figured out eventually that there is nothing wrong with this and there is something else in my code that is just bamboozling me, so I guess i'll figure it out.
valgrind may help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.