Home > OS >  Why does this freestanding program segfault?
Why does this freestanding program segfault?

Time:11-06

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;
}

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related