Crashing is normally caused by an illegal instruction, e.g. accessing invalid memory, dividing by zero, etc. Usually this manifests itself as a well-known exception which is handled by the operating system.
Hanging can be broken up into 2 fairly high level categories:
- Deadlock, usually caused by 2 threads competing for a resource, each requiring a resource held by the other thread to be released. A common cause of this is acquiring multiple locks in inconsistent orders within multiple threads, leading to the common ABBA deadlock pattern (and no this has nothing to do with Swedish pop music).
- Livelock, which means that the code is still actively running, but you have reached a state that you cannot leave. For example:
- The state of 2 processes/threads keep changing, never reaching an end condition
- A while loop where the exit condition will never be satisfied, or an indefinite loop (although this is stretching the definition of "livelock").
Update based on question comment
@Pop, Kristo: Am actually checking on
a code that hangs but I see some
problems on memory leak. But I'm not
really sure if memory leak causes a
program to hang. – jasonline
A memory leak can cause a program to crash, but this depends on various factors:
- Size of leak
- Frequency of leak
- Lifetime of application
Memory leaks may result in 2 bad things - a continual increase in memory usage by the process, and memory fragmentation. Both of these can result in failure to allocate memory down the line, if the OS cannot provide a contiguous block of memory.
In C++, if the new
operator fails to allocate memory, a std::bad_alloc
exception will be thrown. This will most likely be caught by the OS, resulting in a crash (unless you have written a specific handler in your application for this exception, and are able to handle it more gracefully).