vsprintf - safe alternative?

T

Thomas Rogg

Hello NG,

in my program I use the following function:

void write_log(char *format, ...)
{
va_list arg;
char txt[512];

// Get string
va_start(arg, format);
vsprintf(txt, format, arg); // TODO: txt might overflow
va_end(arg);

// Write to stdout
if(debug_console)
write_console(debug_console, txt);
printf(txt);
}

Is there any safe alternative to vsprintf? I do not want to change the
way I am passing the parameters, because I used this function in
thousands of code lines of a project I've been writing for two years now.

Thank you,

Thomas Rogg
 
C

Christopher Benson-Manica

Thomas Rogg said:
Is there any safe alternative to vsprintf? I do not want to change the
way I am passing the parameters, because I used this function in
thousands of code lines of a project I've been writing for two years now.

Sounds like you want vsnprintf().
 
P

Peter Ammon

Thomas said:
Hello NG,

in my program I use the following function:

void write_log(char *format, ...)
{
va_list arg;
char txt[512];

// Get string
va_start(arg, format);
vsprintf(txt, format, arg); // TODO: txt might overflow
va_end(arg);

// Write to stdout
if(debug_console)
write_console(debug_console, txt);
printf(txt);
}

Is there any safe alternative to vsprintf? I do not want to change the
way I am passing the parameters, because I used this function in
thousands of code lines of a project I've been writing for two years now.

Thank you,

Thomas Rogg

None in C89 AFAIK, but C99 has vsnprintf()

vsprintf(txt, sizeof txt, format, arg);

GNU's libc also has the supremely convenient but nonstandard asprintf()
and vasprintf(), which malloc() the buffer for you. Use only if
portability isn't important.

-Peter
 
M

Moonie

INSTEAD OF USING VSPRINTF YOU CAN USE SNPRINTF

SNPRINTF( BUF, SIZE, FORMAT, ARGS );

IT IS FOUND IN A WINDOW ENVIRONMENT AND LINUX BUT NOT DOS.
THERE MAY BE AN OPEN SOURCE FUNCTION AVAILABLE SOMEWHERE IF YOU DO A
SEARCH IN GOOGLE.COM FOR IT.

I HOPE THIS HELPS. YOU DIDN'T SPECIFY PLATFORM AND COMPILER.
 
M

Moonie

_vsnprintf or vsnprintf is lile vsprintf

snprintf or _snprintf is like sprintf

my mistake oops. sorry.
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top