0

At some point my big project's code started getting segmentation fault runtime errors with such stacktrace:

0# std::basic_ios >::widen (__c=10 '\n', this=) at /usr/include/c++/7/bits/basic_ios.h:450
1# std::endl > (__os=...) at /usr/include/c++/7/ostream:591
2# std::ostream::operator<< (__pf=, this=) at /usr/include/c++/7/ostream:113
3# main () at segfault.cpp:11

where last (3#) was always pointing to std::cout lines like std::cout << "hello" << std::endl;

So I brought down my code to this minimal construct which still causes the same error:

#pragma pack(1)
struct Point {
    int x;
};

#include <iostream>

int main()
{
    for(;;){
        std::cout << "hello" << std::endl;
    }
}

Which is built with g++ -std=c++17 segfault.cpp -o segfault -g -Ofast command.

Doing any of the following cancels the error:

  • removing #pragma pack(1)
  • removing -Ofast from g++ options
  • removing for(;;){ (moving std::cout ... out of the loop)
  • moving #include <iostream> before #pragma pack(1)

Tried building with g++ 7.4.0 and g++ 9.2.1 (same results).

Slaus
  • 2,086
  • 4
  • 26
  • 41

1 Answers1

2
#pragma pack(1)
// ...
#include <iostream>

You've applied #pragma pack to the declarations in the standard library header(s) that you include. The standard library that your executable links to at runtime probably did not apply the pragma. Your executable is not compatible with the runtime library that is uses.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thank you, didn't know `#pragma pack(1)` works for all the other declarations - thought only for the declaring one. Fixed it with `#pragma pack(push,1)` / `#pragma pack(pop)` – Slaus Feb 09 '20 at 06:38