What
dannye describes is almost certainly a
charlie horse, a very peculiar sort of cramp, and one of the most painful. Unlike an ordinary cramp, a charlie horse generally involves actual
tearing of muscle tissue, though generally very localized and not so much as to be debilitating after the episode. Ordinary leg cramps usually come either from being
sedentary or from
intense activity.
Cramps of the first type can be prevented by walking around and stretching now and then.
Cramps of the second type have many causes, depending on their location and other factors. In general, stretch well before exercising and make sure you are properly hydrated and have enough electrolytes in your bloodstream.
Otherwise, what dannye said above applies as well to your generic leg cramp.