Codeforces will not be available in the period 01:00-05:00 May, 30 (MSK, UTC +3) because of maintenance. ×

wzhang's blog

By wzhang, history, 7 months ago, In English,

I was doing the following problem:, 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: 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

7 months 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)

  • »
    7 months 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.

7 months 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

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.