Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with sprintf... something stupid?

Tags:

c++

c

printf

Sorry to pester everyone, but this has been causing me some pain. Here's the code:

char buf[500];
sprintf(buf,"D:\\Important\\Calibration\\Results\\model_%i.xml",mEstimatingModelID);

mEstimatingModelID is an integer, currently holding value 0.

Simple enough, but debugging shows this is happening:

0x0795f630 "n\Results\model_0.xml"

I.e. it's missing the start of the string.

Any ideas? This is simple stuff, but I can't figure it out.

Thanks!

like image 361
Jack Avatar asked Oct 25 '22 15:10

Jack


1 Answers

In an effort to make this an actual general answer: Here's a checklist for similar errors:

  • Never trust what you see in release mode, especially local variables that have been allocated from stack memory. Static variables that exist in heap data are about the only thing that will generally be correct but even then, don't trust it. (Which was the case for the user above) It's been my experience that the more recent versions of VS have less reliable release mode data (probably b/c they optimize much more in release, or maybe it's 64bitness or whatever)

  • Always verify that you are examining the variable in the correct function. It is very easy to have a variable named "buf" in a higher function that has some uninitialized garbage in it. This would be easily confused with the same named variable in the lower subroutine/function.

  • It's always a good idea to double check for buffer overruns. If you ever use a %s in your sprintf, you could get a buffer overrun.

  • Check your types. sprintf is pretty adaptable and you can easily get a non-crashing but strange result by passing in a string pointer when an int is expected etc.

like image 168
David Frenkel Avatar answered Oct 27 '22 04:10

David Frenkel