Iterating and dereferencing unaligned pointer to memory causing segmentation fault ? Bug in GCC optimizer?

Viewed 149
// Compiled with GCC 7.3.0, x86-64 -g -O3 -std=gnu++11
// Tested on OS (1) Ubuntu 18.04 LTS, (2) Gentoo

int Listen(... socket)
{
    char buffer[INT16_MAX];
    . . .
    . . . = recvfrom(socket, buffer, ....)
    ParseMsg(buffer)
}

void ParseMsg(uint8_t *const msg)
{
    . . .
    uint16_t* word_arr = (uint16_t*)(msg+15); // if I changed 15 to 16 (aligned to uint16_t) 
                                              // the program doesn't crash

    for(size_t i = 0 ; i < 30 ; ++i)
    {
        word_arr[i] = 1; // after some iterations (around 13) the program crashes with segmentation fault
                         // if i add a print statement inside the loop the program doesn't crash
    }

    // word_arr[20] = 1; // if I assign value not in loop the program doesn't crash 
}

I found some links that talk about this matter:
https://github.com/samtools/htslib/issues/400
https://github.com/xianyi/OpenBLAS/issues/1137
but they talk in processor terminology. Can someone confirm that this bug exists ?

p.s
I ran the code with -O2 optimization flag. Didn't crash

1 Answers

The problem does underline in the alignment of the uint16_t pointer (which should be 2), in combination with -O3 the compiler is trying to optimize your loop using vectorization (SIMD), hence trying to load unaligned argument to SSE registers.

This can explain why it works when:

  1. you change the offset from 15 to 16 - causes the uint16_t pointer to be aligned
  2. with -O2 - disable the vectorization
  3. removing the loop / adding a print within the loop - also disable the vectorization

Please refer to the following link with a question similar to yours and some great elaborate answers:

c-undefined-behavior-strict-aliasing-rule-or-incorrect-alignment

Related