Dumb C++ Mistakes
Posted in :
It seems like I don’t have anything to do with C++ because I have not touched C++ much in this blog. I am a software engineer by trade; programming and debugging is a large part of what I do during the day. I was a little frustrated last two days by a memory problem shown only on UNIX. The program ran fine on Windows, except one or two instances slightly weird results which I tend to ignore. But I could not pass the UNIX test and obviously something is wrong. By looking at the trace back I can tell it’s a memory problem. Memory problem is kind of problem everyone hates. Because it’s usually hard to find the root cause. Dev Partner made the process a little easier because it will show all potential memory overrun and leaks. To my surprise, I made a mistake like the following (very basic C++ mistakes):
char *temp_str = new char[length];
for(int ii = 0; ii < length*2; ii++){
// do something with temp_str[ii]
}
It is a typical memory overrun problem because I only allocate "length" number of char, but I was trying to use "length*2" number of char. It's like use twice the credit limit?
But I am still very puzzlled that my program ran on Windows (without Dev Parter) before the fix. No wonder we see "Windows crash" from time to time
Seriously, in software development we want the problems being uncovered the earlier, the better. Because we don't want our customer run our program and crash.