Thursday, June 18, 2009

Line of code of the day #4

Weee... another LOCOTD ... (no ... that doesn't mean Crazy Tower Defence) ... today i present here the following line of code: 
solution[i] = solution[j] | (~0)&(1<<z)

The most familiarized with C and pointers will notice that if i is not related in bounds with j value (or vice-versa) something really bad will happen with memory access/write... the lovely usual segmentation fault or worse... the line should have look like this:
solution[j] = solution[j] | (~0)&(1<<z)

Or in a more compact form:
solution[j] |= (~0)&(1<<z)

I lost 3h to find where the error on my code was... you see, when instead of j the i was there I was writing in some area, that area was where a pointer inside a struct was, at first I though the error was in functions that manipulate variables of that struct... when I noticed something very strange when I switch some entries on struct... it looked like something impossible to happen, but after I've done it some stuff worked, so struct control looked fine... only answer would me that I was modifying struct data unknowing it... after a bunch of printf's (like... everywhere) I tracked the error down... cost me a lot of time... and now I 'only' have to finish some algorithmic stuff that is implemented, polish some of the code and optimize some memory accesses...

Well... good coding... i hope you have better luck than me...

No comments: