Are all heart malformations hereditary, or are they sometimes just bad luck?

No. Some cardiac malformations are part of syndromes that can be inherited. Others are part of syndromes that occur sporadically. Still others are isolated defects that can have a variety of non-genetic causes.
Sometimes . Can be related to medications taken by mother during pregnancy, infections (rubella is classic), exposure to ionizing radiation, or other exposures can result in congenital (heart and other) defects. Still others occur without being able to identify the cause, and if bad luck is what you want to call it, then so be it.