avoid buffer overflow using sprintf?

S

Susan Rice

How can I rewrite this code to avoid the possibility of a
buffer overflow?

sprintf(errbuf, "%s\nError is: %u: %s\n", errmsg, dwErrCode, s );

Here:
errmsg = a string
dwErrCode = a number
s = a string
I do have value 'errbuflen' = length of buffer 'errbuf'.
I'm just not using it.
Is there any easy way? Or is there only the hard way?
 
M

mlimber

Susan said:
How can I rewrite this code to avoid the possibility of a
buffer overflow?

sprintf(errbuf, "%s\nError is: %u: %s\n", errmsg, dwErrCode, s );

Here:
errmsg = a string
dwErrCode = a number
s = a string
I do have value 'errbuflen' = length of buffer 'errbuf'.
I'm just not using it.
Is there any easy way? Or is there only the hard way?

Use std::strings and std::stringstreams instead:

ostringstream errbuf;
errbuf << errmsg << "\nError is: " << dwErrCode << ':' << s << '\n';

You can retrieve the resulting message with "errbuf.str()" which, if
needed, can be converted to a C-style string like this:
"errbuf.str().c_str()".

Cheers! --M
 
A

Alf P. Steinbach

* Susan Rice:
How can I rewrite this code to avoid the possibility of a
buffer overflow?

sprintf(errbuf, "%s\nError is: %u: %s\n", errmsg, dwErrCode, s );

Here:
errmsg = a string
dwErrCode = a number
s = a string
I do have value 'errbuflen' = length of buffer 'errbuf'.
I'm just not using it.
Is there any easy way? Or is there only the hard way?

std::eek:stringstream stream;
stream << errmsg << "\nError is: " << dwErrCode << ": " << s << "\n";
// Do something with stream.str()

Btw., Hungarian notation like the prefix 'dw' is likely to cause you all
kinds of trouble, and reduces readability, without conferring /any/
advantage with modern tools.
 
M

Markus Svilans

Susan said:
How can I rewrite this code to avoid the possibility of a
buffer overflow?

sprintf(errbuf, "%s\nError is: %u: %s\n", errmsg, dwErrCode, s );

Here:
errmsg = a string
dwErrCode = a number
s = a string
I do have value 'errbuflen' = length of buffer 'errbuf'.
I'm just not using it.
Is there any easy way? Or is there only the hard way?

An easy way to do it is with snprintf(), which lets you specify the
maximum number of characters to store in the output buffer. Your code
would become:

snprintf(errbuf, errbuflen, "%s\nError is: %u: %s\n", errmsg,
dwErrCode, s);

If your C library does not snprintf(), you can get a free
implementation here:

http://www.ijs.si/software/snprintf/

Regards,
Markus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top