Does the new memory allocated always get freed up when program closes? (even if closes unexpectedly from a bug/error etc, or custom close functions)?
Or does it only free the memory if it returns from main?
Does the new memory allocated always get freed up when program closes? (even if closes unexpectedly from a bug/error etc, or custom close functions)?
Or does it only free the memory if it returns from main?
Yes, operating systems usually keep track of the memory allocated by each process and release it when those processes terminate - no matter how.
This, however, is not a valid reason to have memory leaks in your program in general: a program should always actively release the resources (including memory) it acquires, unless there is a really good - and documented - reason for not doing so.
Good reasons could be the dependency of a program's correctness on the order of destruction of global/singleton objects, or the expensiveness of actively freeing allocated memory before termination.
However, while admitting that there could be reasons why a programmer would intentionally avoid releasing memory, please be careful not to develop a too shallow mindset as to what counts as a "good reason" for not cleaning after yourself.
I would encourage you to get used to write code that does release the memory it acquires, and document explicitly in a very clear form every situation where you are not going to follow this practice. Again, while there might be corner-cases that require this, releasing or not releasing acquired memory always has to be an active, intentional decision of the programmer.
NOTE: Quoting Steve Jessop from the comments, another good reason why you would not want to actively release memory is when your program needs to be terminated because it somehow reached an unexpected state - perhaps one that violates an invariant, or a pre-condition of a certain function. Usually, violating a precondition means Undefined Behavior.
Since - by definition - there is no sane way to recover from UB, you may want to immediately terminate your program rather than performing further actions that could have any outcome - including highly undesirable ones.
Not all operating systems (in modern OS this is not a problem) do this operation and you had better not rely on this property. You can have a look at here: What REALLY happens when you don't free after malloc?