September 2019 Update

New! We're moving to the new forum!

ALL new Blog posts will be on the forum.

Please join us there.

This Blog will no longer be updated...

Saturday, September 7, 2019

Stupid coding mistake

Sometimes it doesn't pay to code when you are really tired.  I was doing ok, been at it most of yesterday and all night last night, it's 6:30am now.  I was working on something, and I noticed a bit of code that took 4 lines, and I figured I could cut it down to one without losing clarity, meaning if I come back and look at it, can I tell what it's doing easily?  That is generally my number one rule, it doesn't matter how much extra code it takes, it must be readable and understood easily. Anyhow, you can see a before and after of the clearStr method.   The first one works...

The second one doesn't work.

The first one for example, let's use a string "testing", it gets the length, 7, and then loops 0-6 setting the character to null for each. strlen() returns the number of characters BEFORE the null terminator.

The second one, loops from 0 to the length of the string, but the first time through, it sets the first character to a null, which makes the length of the string 0, since there are no characters BEFORE the null. However, there ARE characters AFTER the null...
Before: "testing0"  0=NULL Char
After: "0esting0"

Then along along comes new text for the string, lets say the new string is "pass", and it is added one character at a time, so it adds 4 characters "p" then "a" then "s" then "s"
so the string looks like this as the characters are added...

You end up with the string "passing" not "pass"

For the first example, it would start with 
Before: "testing0"
After: "00000000"

Again, 0 = NULL Character..

Now, if we add 4 characters like before, "pass" the string becomes "pass0000" which is "pass"

Now go back and look at the code again, at first glance, it looks like they do exactly the same thing, especially if you are really tired :)  That's my excuse...  It took me nearly two hours to find the problem, after I eliminated everything else, this was the only other change I had made, so I switched it back, and problem solved, thats when I looked carefully and saw why.

No comments:

Post a Comment

Any comments deemed off topic or offensive will be removed