Roger Rabbit
Roger Rabbit

Reputation: 98

vsnprintf crash program in case %s is set with an integer

I'm writing a logger in C++ and to simplify entering lines I use vsnprintf function to build log line

void CLogger::RegManLog(const LogLevel & logLevelMask, char * Format, ...)
...
...
va_start(marker_, Format);
vsnprintf(buffer_ ,MaxLogBuffSize , Format, marker_)
va_end(marker_);
printer_ += buffer_;
...
...

every thing works great up until I accidently enter a number into a string

integer test = 10; eg.: "now I'll show a string %s" , test

tried to add "try and catch", but I think vsnprintf does have throw, so it crashes any way. tried to get return value from vsnprintf, it return value, while string are fine, when reaching the same issue, it crashes

any thoughts of I can i solve this issue?

thanks

Upvotes: 1

Views: 3953

Answers (3)

Vadim
Vadim

Reputation: 2865

  1. %s expects to get a char*. When you pass in 10, it treats it like an address, goes there and kills your program.
  2. If you wish to print integers, use %d. For more information look at http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html
  3. In C++ it is best to use other methods to accomplish what you need, like std::stringstream

Upvotes: 3

Xaqq
Xaqq

Reputation: 4386

Well, when passed to printf() and family, the %s formatter is here as a placeholder for a -eventually const- char * pointer.

What is happening, is that your integer is read as a pointer, and it's likely that the memory address (10 in your example) is invalid.

Upvotes: 1

dunc123
dunc123

Reputation: 2723

You could avoid printf and friends and instead use std::stringstream or boost::format

Upvotes: 1

Related Questions