Wednesday, May 30, 2007

A bug

A stupid bug in my program:

vector <> content;
vector <> cp_array; // content pointer array

Constructing content and cp_array at the same time, using cp_array[x] = &content[y]. Later I found some pointers in cp_array didn't point to the correct content element. I doubted the logic of my program first, and then looked for all pointer assignments, but all seemed to be correct. After step by step debugging and printing intermediate array values (damn, it's hard to debug stl using gdb even though none optimizations were switched on), I found the content cp_array pointed to changed after a content.push_back(a), it is the push_back operation that caused content to reallocate memory and then what cp_array pointed to was nullified because the address of content vector was changed.

What I've learned: Do not use pointers on dynamically allocatable content, use indices instead.