welcome guest
login or register

22nd of February 2015


Comments

Now this one was tricky!

My code crashed with a segmentation fault - it appeared to be somewhat random; sometimes I could run my algorithm 1000 times all fine, and sometimes it crashed on 400th run. And a segfault is typically caused somewhere earlier in the code, so you can't find the cause by spotting the crashing point. I had to experiment with commenting out different parts of the code until I got it narrowed down to a single line:
weatheryear[i].temp=currtemp+0.5;

At first I thought that i is somehow running outside the array, but no - it was always within 0..364 (I'm precalculating a temperature value for each day of a year). Then what? currtemp is a float. And temp is a signed char, which is enough to store values ranging from -50 ... +50. And currtemp is always inside this range,too. Can you spot the bug?

Well, I don't know if this is documented somewhere, but this was remedied by changing temp to be a signed int. So, somehow, in some cases, converting a float to a signed char causes a memory leak. I didn't know that!

Wow, that sounds like a compiler bug to me! I don't think casts should ever do that, should they? Or do you have some kind of pointer-cast-dereference funny-business going on?

No pointers involved, so I guess sometimes something goes wrong in float to char conversion.

I tried to search gcc buglist, but couldn't find this one reported - so it might also be somewhat system / hardware dependent, or anything like that.

So, in any case, I'm happy that I found it, and that there is an easy way out. It is just my old-school way of "never reserve more memory you are actually going to need" - but since we are no more living the times of Commodore 64, an array with 365 elements isn't that big. So no need to worry, if the array contains a variable of type "int", but actually only uses less than 8 bits to store the values.

OK. Now as I have a base temperature for each day, I'm going to make it so that hour by hour the base temperature is altered by other variables. Like, if it is clear sky with sunlight, it increases the temperature. And a strong wind from north will decrease the temperature. And things like that.

It already tracks ice and snow thickness, so eventually we are going to see summer / winter transitions being more gradual and unpredictable.

Pages

Add new comment

CAPTCHA
Please reply with a single word.
Fill in the blank.