1

In a C program, if I try to use malloc and for some reason the pointer is NULL, I will terminate the program with exit(1); as without that block of memory the program is essentially unusable. Upon using exit(1); should I be releasing all of the memory I had allocated during the program or does that happen automatically?

11
  • 2
    Its better to free it up to avoid memory leaks. Commented Jul 8, 2022 at 12:01
  • 1
    If malloc returns a null, one may suspect heap corruption, so a clean release does not seem relevant. (But another possibility is that you are claiming too much memory.) Commented Jul 8, 2022 at 12:04
  • 1
    As @SupportUkraine calling exit() is usually for emergency termination. Commented Jul 8, 2022 at 12:12
  • 2
    @MarkoTaht if the program needs an unexpected exit it usually best to do the minimum necessary to inform and clean up. Something has gone wrong, and if you then try to handle all subsequent errors "cleanly" you can end up down a rabbit hole. I agree though, that in a typical return from main() it's good practice to clean up. If you can't easily do that, it perhaps shows a poorly organised data structure. Commented Jul 8, 2022 at 13:00
  • 3
    @MarkoTaht: If there is an OS bug reclaiming memory, calling free is not expected to help. free updates records internal to the process. Commented Jul 8, 2022 at 13:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.