# sprintf........am I safe or am I killing my computer?

This topic is 4323 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

[c++] I used to have a function that converted a string of text and a list of numbers into a char array, but now that I see the sprintf command, my humble function seems obsolete. So I'm wondering if what I'm doing is safe. Here's the code:
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
char *buffer;
char source[] = "integers (%i %i %i) text (HI WORLD!) some...thing (%0.25f)";

sprintf(buffer, source, 1, 2, 3, 10.1);
cout << buffer << endl;

getchar();
}

I've seen people declaring buffer as char buffer[255] and things like that, but I don't know what's best. I just want to convert it quickly and not use any more memory than is required. Thanks

##### Share on other sites
you are writing in a undefined memory area when not declaring memory space for char *buffer;

[SOURCE]do like thischar buffer[4096];sprintf(buffer,"PI:%f",3.14f);or using std::stringstreamstd::stringstream w;w << "PI:" << 3.14f;std::string str = w.str();[/SOURCE]

##### Share on other sites
You're never safe with C strings.

http://gpwiki.org/index.php/Beginner_FAQ

##### Share on other sites
Several Things.
Your overwriting some random place in memory. This is bad (very unsafe). And 255 bytes is nothing for a computer.

sprintf is bad to use since it is unsafe (sprintf is a source of many bufferoverflow exploits)

snprintf is non standard but common, you should always use it instead of sprintf (This is one of the few places I'd encourage being nonstandard).

Even better is the C++ library's stringstream, boost::Format and boost::lexical_cast since they use C++ strings which are much safier, and less error prone.

##### Share on other sites
when using C++, it's better to just use <string> instead of char*
also it's redundant to use <stdio.h> and <iostream> use one or the other, preferrably <iostream>.
one more thing, it's not <stdio.h>. it's <cstdio>.

if i've misunderstood the ultimate purpose of your venture, i apologize humbly.

##### Share on other sites
Wow, thanks a ton you guys. I've heard of boost before, but now I've actually downloaded it and it does exactly what I was needing. Thanks for all the info everyone, I learned a lot (this also explains why my code would sometimes work, and sometimes crash... :P).