Jump to content
  • Advertisement
Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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;
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 this post

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

do like this

char buffer[4096];

or using std::stringstream

std::stringstream w;

w << "PI:" << 3.14f;

std::string str = w.str();


Share this post

Link to post
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 this post

Link to post
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>.
i would advise using Leadorn's stringstream example.

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

Share this post

Link to post
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).

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!