Sign in to follow this  
Cornstalks

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

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


[SOURCE]
do like this

char buffer[4096];
sprintf(buffer,"PI:%f",3.14f);


or using std::stringstream

std::stringstream w;

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

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

[/SOURCE]

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this