When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

wzhang's blog

By wzhang, history, 4 years ago, In English

I was doing the following problem: https://codeforces.com/problemset/problem/1244/D, and was very confused when I tried to add code to print out the answer at lines 120-123, it segfaults at line 57 according to gdb. When I remove the code to print out the answer, no segfault occurs. I am incredibly confused. I removed all pragma's and macros, additional libraries, etc. and this error still persists. Does anyone have an idea why this is happening?

Here is the code: https://pastebin.com/ufrxhLtR Compiled with g++ -Wall -g with no errors or warnings, output of gbd when run:

Program received signal SIGSEGV, Segmentation fault. 0x0000555555554b4b in main () at 1244D.cpp:57 57 cin >> N;

Thanks in advance.

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

It runs on codeforces without any error.

Given that the line right below that line creates a huge local array (on the stack), it's likely that it causes a stack overflow.

See also: c++ — Segmentation fault on large array sizes — Stack Overflow (also includes a solution to increase the stack size on Linux)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Thanks so much for the help! I fixed it by declaring all of those large arrays in global scope.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

A program might crash when printing to console (and/or on exit from a function) in case of stack corruption. This usually means accessing arrays out of bounds. If you use GCC, there are some compiler options to catch these errors, see https://codeforces.com/blog/entry/15547.

Technically, making arrays global just move them to global memory (sorry for saying obvious), and so the program's globals might be corrupted instead of stack.

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I had the same problem in a contest in codechef. I reached out to them via mail, and apparently it was an array out of bounds. They said that array out of bounds in a C style array is not very strict and sometimes it goes undetected. And hence using vectors or std::array is a better option if you think there might be an array out of bounds

I tried to report it as a bug. Here is a bug report response

Here are the links to my answers

https://www.codechef.com/viewsolution/30545573 https://www.codechef.com/viewsolution/30545583