0

There are already some approaches for this question. ¹ ² ³

But this one is completely different! If I comment out std::flush line, Segfault occurs, but if I add this line, The Segmentation fault doesn't occur!

int Stm32Serial::writeToSerial()
{
    /// TODO Write handle for writing if necessary
    /// int serial_write_ret;
    if ( USE_USB )
    {
        usb_port.writeBytes ( stm_buf_t, stm_buf_t[LENGTH_INDEX] );
        return SERIAL_RET;
    }
    else
    {
        std::cout << std::flush; // TODO HACK Remove it!
        serial_port.sendBuff ( stm_buf_t, stm_buf_t[LENGTH_INDEX] );
        return SERIAL_RET;
    }
}

Also I tried gdb; I'm using this function in ROS with this debug technique and compiling with -g option but it doesn't print function names

Program received signal SIGSEGV, Segmentation fault.
__mempcpy_sse2 () at ../sysdeps/x86_64/memcpy.S:142
142 ../sysdeps/x86_64/memcpy.S: No such file or directory.
(gdb) bt
#0  __mempcpy_sse2 () at ../sysdeps/x86_64/memcpy.S:142
#1  0x6564656563786520 in ?? ()
#2  0x20726f7272652064 in ?? ()
#3  0x6c6f687365726874 in ?? ()
#4  0x2e30203a79622064 in ?? ()
#5  0x202c323537373431 in ?? ()
#6  0x697420656c637963 in ?? ()
#7  0x36312e30203a656d in ?? ()
#8  0x2c31343936373632 in ?? ()
#9  0x6f68736572687420 in ?? ()
#10 0x32302e30203a646c in ?? ()
#11 0x742064616572202c in ?? ()
#12 0x312e30203a656d69 in ?? ()
#13 0x3530333430353233 in ?? ()
#14 0x657461647075202c in ?? ()
#15 0x30203a656d697420 in ?? ()
#16 0x373430353233312e in ?? ()
#17 0x74697277202c3234 in ?? ()
#18 0x203a656d69742065 in ?? ()
#19 0x3637363236312e30 in ?? ()
#20 0x006d305b1b333637 in ?? ()
#21 0x00007fffffffbbf0 in ?? ()
#22 0x00000000ffffbbd8 in ?? ()
---Type <return> to continue, or q <return> to quit---
#23 0x00007fff00000000 in ?? ()
#24 0x0000000000000000 in ?? ()
(gdb) 
  • Looked for LENGTH_INDEX and stm_buf_t[], there are ok.

And also; If I call std::cout << std::flush; from another place, which has a call of this function, It handles Segfault too!

...
genSum ( stm_buf_t );
writeToSerial();
std::cout << std::flush;
...

What can be my next approach?

Orhan G. Hafif
  • 379
  • 5
  • 21

1 Answers1

4

An experienced nerd will note that the stack is full of ASCII. This is almost always a sign of buffer overflow in a strcpy or similar on a local variable.

I converted some of the stack addresses from hex to ASCII. It appears to read backwards.

rorre dedeecxe rorre dlohserht.0 :yb d ,257741it elcyc61.0 :em,1496762ohserht 20.0 :dlt daer ,1.0 :emi50340523etadpu ,0 :emit

The first bit appears to say 'threshold error exceeded error'. Looks around in you code or input file for this text and see where it is used in the code. There is almost sure to be a memory copy that is overwriting the local buffer.

As the comment noted, Valgrind will often find this sort of issue.

Matthew Fisher
  • 2,258
  • 2
  • 14
  • 23