Monday, March 9, 2009

A tricky error, when using std::string with *printf funtions

All of us know what this code (listing 1)will do...

char * szName = "Ex";

printf("%s", szName );

Will anybody tell what will be the result of these lines(listing 2)...


std::string strName = "Zed";
printf("%s", strName);

Ladies and gentlemen... listing two will cause your program to crash. This is a very common mistake made by programming newbies... though an experienced pro may also do the same...

The right way to print the string is

std::string strName = "Zed";

printf("%s", strName.c_str());

such errors are very difficult to spot... Because when reading the code, one often unconsciously considers these lines are correct...

Now people will ask that why in the world will someone create such a ridiculous blend of C and C++... The answer is... I don't know why... But anybody is absolutely free to mix the two compatible languages into a cocktail... I myself did this... when I was new into the dark realm of C/C++ programming... I had my own reasons... others will have their own...

note: *printf means any of the following funtion calls {printf, sprintf, fprintf}

3 comments:

Feel free to talk back...