Need some help on how to deal with Segmentation Fault

I’ve solved a few problems from the ico online archive and it turns out that there are always a couple of test cases at the end which give a runtime error as segmentation fault. I googled a bit and found it was memory access problem, but am unable to fix it. I won’t go into details of the problems, but can anyone suggest a few tips to be kept in mind to avoid this error?

There are several types of segmentation fault, it’s hard to help without details.

Invalid memory access is the most common. Here, practice is the main advice. By practice I mean:

  • Code as concisely as possible. Read other people’s code and learn possible implementation tricks to keep it simple and short.

  • Use your own coding standard. For instance, always use i as a for-loop variable, j for a second nested for-loop, k for a third, etc. Same for array indices and so on. This will help avoiding typo mistakes using the wrong variable to access an array position.

  • Use more memory than you need. If N <= 10000, don’t use an array with 10000 or 10001 positions. Use 10000 + 100 for example. This will avoid common bugs when you are using position N+1 or N+2 for convenience or a mistake due to using <= X instead of < X. Note: I only advice doing this in competitive programming as it is bad software engineering.

Check memory limits. Exceeding the global memory limit gives “Memory limit exceeded” but a somewhat harder to spot case is exceeding the stack memory limit. Declaring large arrays locally in a function or infinite recursion are some of the possible causes.

1 Like