Opened 10 years ago

Closed 10 years ago

#7661 closed Bugs (invalid)

lexical_cast throws exception when strings have more than one null terminators

Reported by: pengxu7@… Owned by: Antony Polukhin
Milestone: To Be Determined Component: lexical_cast
Version: Boost 1.52.0 Severity: Problem
Keywords: Cc:

Description

Hello,

I got following exception while using boost 1.52.0: " terminate called after throwing an instance of 'boost::bad_lexical_cast'

what(): bad lexical cast: source type value could not be interpreted as target

"

Here's the sample code: " #include <iostream> #include <boost/lexical_cast.hpp>

int main( int argc, char argv ) {

std::string m = "0"; m += '\0'; int i = boost::lexical_cast<int>( m ); std::cout << "Got number " << i << std::endl;

} "

Thanks, Peng

Change History (5)

comment:1 by Marshall Clow, 10 years ago

I don't think this is a bug.

If you catch the exception, and display the what(), it says:bad lexical cast: source type value could not be interpreted as target.

I believe that what has happened is that it attempted to convert the two character sequence "0\0" to an integer, and that failed. This is the same thing that would happen if you appended (say), a 'Z' instead of a '\0'.

Why would you expect that to succeed?

comment:2 by pengxu7@…, 10 years ago

If you print the std::string starting with 'm' following by multiple null terminators in std::cout, you will only see "0" not "0\0". I expect boost::lexical_cast to do the same for std::string, does it make sense?

comment:3 by Marshall Clow, 10 years ago

A std::string is not a null terminated string.

The string that you have constructed is two characters long. The first character is a '0' (ASCII 48), and the second is a NUL (ASCII 0).

When you print that string, it prints _two_ characters - it's just that your console does not display the NULL.

If you build this program and run it, you would see "m" printed on your console.

#include <iostream>
int main( int argc, char *argv[] ) {
	std::string m = "0";
	m += '\0'; 
	std::cout << m;
}

But if you redirect the output to a file, and look at the file, you will see that the file is two characters long, with the second being the NULL.

comment:4 by pengxu7@…, 10 years ago

ok, pls close it as it's an invalid bug.

comment:5 by Marshall Clow, 10 years ago

Resolution: invalid
Status: newclosed
Note: See TracTickets for help on using tickets.