Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Is it ok to use exit(1) to abort the program or should you attempt to return 1 from the main()?

I have used exit(1) extensively in my code because it does (I hope) exactly what I want - abort the program. I nicely print an error message (or put it into stderr), and then I just leave.

But I heard some schools of thought that this is bad for some reason and I don't understand why. The amount of work one would need to return an error value from every function where it is possible, and then navigate through cascading returns back to main so the program exits "naturally"... Is there a difference?

Are there specific scenarios where it matters? Even when I use errno and perror(), it is still much easier to just exit(1) from the point where the error occurred and without making the code less readable.

Do I have your blessing to use exit(1) ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

It's a choice to make for yourself.

If you're writing a library, you really ought to report failure to the caller, which may be able to recover in ways you can't internally, and which might need to perform other cleanup that's not done by registered atexit() handlers.

If your code might be called from C++ or other high-level languages, then again, don't unilaterally exit, as that prevents destructors running to perform similar cleanup.

When you check memory use using Valgrind, then exit() will leave lots of objects in the "still accessible" state, making it harder to find your real leaks.

So I generally recommend returning from main(), but would tolerate some use of exit() in program-specific code that's never going to end up in a library.

over 4 years ago · Santiago Trujillo Report

0

The C library function void exit(int status); terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.

So, we are know that exit() function causes to kill the current program, but remember to free() any heap allocated resources (if you can) before calling the exit() function. So, using the exit() is absolutely okay.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!