![]() |
|
sprintf() and size restrictions |
OnlineCop
Member #7,919
October 2006
![]() |
I have a small char array (let's say 10 bytes) that I want to pass into sprintf(). What happens if sprintf() pushes too much onto that array? Here's an example of how to reproduce this:
This will crash with a SEGFAULT (so if you run it, do it through a debugger). Apparently, sprintf() is unsafe and "keeps going until it's done" but doesn't do any bounds checking. Is there a "safe" sprintf() function, like sprintnf() that I can use to ensure that I don't exceed a specified size?
|
Kitty Cat
Member #2,815
October 2002
![]() |
Quote: Apparently, sprintf() is unsafe and "keeps going until it's done" but doesn't do any bounds checking. Of course, because you don't tell it how big its bounds are (it's not psychic). Quote: Is there a "safe" sprintf() function, like sprintnf() that I can use to ensure that I don't exceed a specified size?
snprintf -- |
OnlineCop
Member #7,919
October 2006
![]() |
Perfect. Thanks, KC!
|
Thomas Fjellstrom
Member #476
June 2000
![]() |
I personally like using the return value of snprintf, and passing NULL to the string arg so it just calculates the total length, and then allocating a properly sized buffer to do it again. Another option is to use GCC's asprintf. It allocates the buffer for you. -- |
Goalie Ca
Member #2,579
July 2002
![]() |
Uhh... you're using iostream and sprintf? Why??? Use #include <strstream> ------------- |
bamccaig
Member #7,536
July 2006
![]() |
Thomas Fjellstrom said: I personally like using the return value of snprintf, and passing NULL to the string arg so it just calculates the total length, and then allocating a properly sized buffer to do it again. O_o
-- acc.js | al4anim - Allegro 4 Animation library | Allegro 5 VS/NuGet Guide | Allegro.cc Mockup | Allegro.cc <code> Tag | Allegro 4 Timer Example (w/ Semaphores) | Allegro 5 "Winpkg" (MSVC readme) | Bambot | Blog | C++ STL Container Flowchart | Castopulence Software | Check Return Values | Derail? | Is This A Discussion? Flow Chart | Filesystem Hierarchy Standard | Clean Code Talks - Global State and Singletons | How To Use Header Files | GNU/Linux (Debian, Fedora, Gentoo) | rot (rot13, rot47, rotN) | Streaming |
Thomas Fjellstrom
Member #476
June 2000
![]() |
pretty much, though I'd do it like so: Just to be obvious about the NULL bit. -- |
BAF
Member #2,981
December 2002
![]() |
Stringstream = better. |
OnlineCop
Member #7,919
October 2006
![]() |
Is there a sprintf()-style function available for std::string? If so, you wouldn't need to worry about memory allocation/deallocation or string length. Does std::stringstream allow you to do this?
|
LennyLen
Member #5,313
December 2004
![]() |
Quote: Stringstream = better.
Though you get problems trying to use it in C.
|
BAF
Member #2,981
December 2002
![]() |
OnlineCop: yes. |
|