NetHack segfaults in certain rare situations where a function expects the game to be in a state that it is not. This always indicates a bug in the code (with the exception of the game features in Slash'EM Extended that are intentionally designed to corrupt memory). The most common reason is the nonexistence of something that a function assumes will exist.
Depending on the operating system used, the behavior can be slightly different; on Windows, Nethack closes and often displays a message saying "NETHACK.EXE has stopped working"; on Linux, you normally get a "Segmentation fault" error message printed at whatever location the cursor happens to be onscreen (followed by a prompt); and most public servers will handle the segmentation fault internally and just send you back to the launch screen (eu.un.nethack.nu additionally sends a message to its IRC channel when this happens).
A segfault will leave files on disk exactly as-is, without any attempt to save the game. In most cases (i.e. any codebase that is not derived from NitroHack, with the INSURANCE compile-time configuration option set and the in-game checkpoint option set), the game will be left in a state where it needs recovery, and after recovery, will return the game to the state at which it was in when the player entered their current dungeon level, or saved (whichever is more recent).
In the case where the game can detect an impossible state before it happens, you get a panic instead. This has clearer messages than a segfault, and often recovers in a different way, because the game has a chance to handle it. (For example, sometimes you will get an "emergency save" file created.)
If you are working on developing a NetHack variant (or NetHack itself!) on Linux or Mac OS X, you can configure your terminal so that a segfault leads to a useful "core dump" file that can be opened in a debugger to allow you to know what went wrong. The command to use depends on the operating system and shell you are using. For Linux with bash, you can use this command before running the program:
ulimit -Sc unlimited
A user has suggested improving this page or section as follows:
"commands for other shells and operating systems"
Note that many operating systems will only save one core dump (per program, or per working directory) at a time, so you will need to delete the old one before you can get new ones.
In DynaHack and NetHack 4 (and theoretically in NitroHack, although the mechanism normally fails in practice), the game will normally be able to recover from a segfault automatically (returning to the start of the turn in DynaHack, or the exact point of the segfault in NetHack 4), although if the bug that caused it has not been fixed in the meantime, the game will normally segfault in the exact same way again.