How can I immediately close a program in C?

Syntax_Error picture Syntax_Error · Nov 1, 2011 · Viewed 89.2k times · Source

I am writing C code, in which I am analyzing some data. I have set the program to handle only 100 data inputs. When it has more than 100 inputs, it is giving a segmentation fault. I want to create a way so that when the number of inputs is above 100 the user will be warned and the program will terminate. I know how to do it from the main function by simply return 0, however I am multiple function calls away from main and it is difficult to do that even a return 0 in this function will keep it looping.

Is there any immediate way to terminate the entire program without being in main?

Answer

K-ballo picture K-ballo · Nov 1, 2011

The standard function exit is what you are looking for:

Terminates the process normally, performing the regular cleanup for terminating processes.

First, all functions registered by calls to atexit are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.

The status argument is returned to the host environment.

It would be better though if you fixed the segfault error.