Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this freestanding program segfault?

Tags:

c++

I've found an interesting behavior that I cannot explain. I wrote this very simple program that segfaults without apparent reason. Please, can someone explain what is happening here?

  • The program is run in Ubuntu (I don't know if that matters).
  • No includes, no libraries, no link to stdlib. No dependencies whatsoever.

I've tested that the segfault goes away when any of the following happens:

  • stdlib is linked (and renamed _start to main, removed extern "C", etc.)
  • GCC is used
  • Optimizations are enabled

The following is the one and only code file for the program, lets call it main.cpp.

Build it with: clang main.cpp -nostdlib.

struct A
{
    A () = default;
    A (const A &) = default;
    // A (A &) = default;

    char * a = nullptr;
    unsigned long long b;
};

struct ConvertibleToA
{
    ConvertibleToA() = default; // default constructor
    operator A() { return m_a; } // conversion to type A
    A m_a;
};

extern "C"
void _start()
{
    ConvertibleToA my_convertible{};
    A my_a = my_convertible;
}
like image 361
DeltA Avatar asked Jul 04 '26 09:07

DeltA


1 Answers

Check your stack alignment. For the SysV ABI, rsp is guaranteed to be 16-bytes aligned at program entry. However, a normal function expect rsp to be 16-bytes+8 aligned, because of the address pushed by call.

Clang uses SSE aligned instructions which will crash, GCC doesn't.

like image 84
ElderBug Avatar answered Jul 05 '26 22:07

ElderBug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!