I need to tell you the story of my MOAB (Mother of all bugs).
I need to write some stuff in C (which i am fairly used to) and have a function that allocates memory for a Matrix on the heap. The matrix has a rows and columns property and an associated data array, so it looks like this
struct Matrix{
uint8_t rows;
uint8_t columns;
uint8_t data[];
I allocate rows*columns + 2 bytes of memory for it.
I also have a function to zero it out which does something like this
for(int i=0; i < rows*columns;i++){

Let‘s come to the problem:
On my Mac the whole stuff works and passes all tests. We tried the code on a Linux machine and suddenly the code crashed in various places, sometimes a realloc got an invalid pointer, sometimes free got an invalid pointer and basically the code crashed at arbitrary points randomly.
I was confused af because did i really make THAT many errors?

I found out that all errors occured when testing my matrices so i looked more into it and observed it through the debugger.

Eventually i came to the function that zeroes out my matrix and it went unusually high and wondered if my matrix really was that big.
Then i saw it
The matrix wasn‘t initialised yet
It had arbitrary data that was previously in the heap.
It zeroed out a huge chunk of the heap space.
It literally wrote a zero to a shitload of addresses which invalidated many pointer.

You can imagine my facepalm

  • 6
    Memset, please! 😭
  • 0
    @irene I'd also suggest memset, but in this case it wouldn't help. Uninitialized variables may or may not be automatically initialized, depending on variable declaration, compiler, optimization level and other magic.

    Best practice is to always initialize at least any scalar types. It also shows the intention of the implementor.
  • 1
    @ddephor correct. But setting every 4 bytes separately is painful 😭
  • 1
    @irene Yeah right. But I've seen worse stuff, already ranted about some time ago: https://devrant.com/rants/556473/
Your Job Suck?
Get a Better Job
Add Comment