It took me hours and hours to find this bug today. The following code works (even though in my opinion it shouldn’t). The code is more pseudo- than real. The real thing wouldn’t be understandable anyway.
Matrix *m1 = (Matrix*)malloc(sizeof(Matrix));
free(m1);
useMatrix(m1);
The code did exactly what it was supposed to do even though I free up the memory in between the calls in a more complicated scenario. However, when I modified the code to this
Matrix *m1 = (Matrix*)malloc(sizeof(Matrix));
free(m1);
Matrix *m2 = (Matrix*)malloc(sizeof(Matrix));
useMatrix(m1);
I got a segfault and couldn’t figure out why creating a new object would cause my program to crash. In my opinion a more sensible scenario would be that the first code snippet would cause the program to segfault, so I knew that there was something wrong already.
Bizzare… The platform is OS X Leopard with gcc 4.0.1. The current theory is that even though I free the memory, the contents are still intact and the OS is able to use them, but once I malloc again, the same region of memory got overwritten and the old pointer was marked invalid. I don’t know…
Anyone who comes across this and has a good way of explaining this awful behavior to me, I would be happy to hear it.
George, did you mean to type `useMatrix(m1)’ in the second example? Because you already free’d that matrix. Should be `useMatrix(m2)’ …
I think that was the point of the bug – the matrix is freed, but still accessible until you allocate another one….