Tomas
Tomas

Reputation: 1397

Float to Char Array to std::string

I'm having a bit of a problem with this piece of code:

string StringServices::ToStringf(float value)
{
    char buffer[10]; 

    sprintf (buffer, "%f", value);

    return  (string) buffer; // signal SIGABRT
}

Its been working previously and continues to work for other calls, but I currently get a SIGABRT on the return, when the function is being passed -211.0

The buffer loads up fine, and I'm really not sure why this isn't working. Can someone who understands std::string and c strings a lot better then me help me out here?

Upvotes: 1

Views: 3205

Answers (2)

Andrey Agibalov
Andrey Agibalov

Reputation: 7694

The main problem with C and its string functions is that you have to do too much work manually. You also have to make too many decisions when you write in C. One of the trivial issues is buffer overflow. Consider this code:

char buf[5]; // 5 chars, ok
sprintf(buf, "qwert"); // 5 letters, ok

You're going to have problems with this code, since when talking about strings, 5 chars means 4 letters + '\0'. So, you may try:

printf("'%s'\n", buf); // you'll probably get 'qwertIOUYOIY*&T^*&TYDGKUYTU&*#*#T^&#$T67...'

What you do with your code is a trivial buffer overflow :-)

sprintf() just has no way to check the size of buf, so a piece of memory that goes right after buf can get corrupted.

Upvotes: 1

Mark B
Mark B

Reputation: 96241

You probably overflowed your buffer because you're not using snprintf. You have this tagged C++ so do it that way:

std::string buffer = boost::lexical_cast<std::string>(value);

Or without boost use a string stream:

std::ostringstream os;
os << value;
// os.str() has the string representation now.

Upvotes: 7

Related Questions