Find an error in following snippet.
Today I will like to demonstrate how small mistakes can puzzle you for quite a lot of time.
This was the error which I found while working on code. The simplified form goes thus:
#include <string>
using std::string;
void foo(const char *str){
.... //Lot of stuff here
}
bar(){
....
char *temp1 = "Part1";
char *temp2 = "Part 2";
foo( (string(temp1) + string( temp2)).c_str());
...
}
main(){
...
bar();
....
}
This code was working perfectly till one day it started crashing on release build, and it was crashing somewhere there in function foo. It was a trap which my teammates ignored and I was the one who wrote function bar, but foo was written by someone else. Now we had an option to put always part of code in debug flag. Which one of my previous company did (if you want to know of the details, please contact me offline on abhilekh.agarwal at gmail). Or better option was to fix it.
Can you find the bug in here. Scroll down for an answer.
.
.
.
.
.
.
.
.
.
.
.
.
The answer is:
Problem was at line
foo( (string(temp1) + string( temp2)).c_str());
Actually what happens is that string is temporary and so C-string created is temporary. And any variable in foo could have used the memory. The solution was the change
string temp3 = string(temp1) + string( temp2);
foo( temp3.c_str() );
Hope some of you learned something out it, and for others it was an obvious, but I hope all of you would have liked it.













