468,512 Members | 1,288 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

safe version of sprintf

Hi,

does exist a safe version/way of sprintf to prevent a buffer overflow by
using in this manner?

char* format = "0x%0.4X\n";
char buf[4];

sprintf(buf, format, number);

where the format can change at runtime? The buf size is fixed at compile
time.

In the example above the buffer is to small and it's written random in
memory.

Thanks
Olaf
Jan 25 '08 #1
1 3638
Olaf wrote:
...
does exist a safe version/way of sprintf to prevent a buffer overflow by
using in this manner?

char* format = "0x%0.4X\n";
char buf[4];

sprintf(buf, format, number);

where the format can change at runtime? The buf size is fixed at compile
time.
...
There are always at least two ways "to prevent a buffer overflow". One is the
make sure that your buffer is always big enough for the data you are trying to
write into it. Another is to truncate the data when it hits the limit of the
buffer. The first question you should be asking yourself is which one you really
need.

The latter prevention strategy is of very limited use since, even tough it does
prevent the overflow, it usually provides no useful result and no meaningful
continuation strategy. It is mostly useful in situations when you want to abort
your program anyway, but you'd prefer to exit more-or-less gracefully with your
own diagnostic message instead of the inelegant "segmentation fault, core dumped".

If that's not what you want to do (is it?), then you'd better off sticking with
the former strategy. Which brings the question of where is the requirement of
the buffer size being fixed at compile time comes from?

--
Bes? regards,
Andrey Tarasevich
Jan 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Pete | last post: by
9 posts views Thread by Jody Gelowitz | last post: by
1 post views Thread by grahamo | last post: by
7 posts views Thread by Jim Showalter | last post: by
18 posts views Thread by jeff_j_dunlap | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.