Before you scratch your head how sacrificing oneself for others could be immoral consider the classic dilemma, of too many people in a life boat when a storm approaches or similar ones, which deal with the issue of killing someone innocent to save others. According to catholic teaching this is immoral, as killing an innocent is always evil and therefore cannot be outweighed by any good one might think to achieve by the act.
Now the problem:
If just one person leaves the life boat it would be enough to save the rest. While still thinking about the problem, one declares that its better that he dies than that all die and readies himself to leave the boat for certain death.
By that he still takes the life of an innocent to achieve some greater good.
Is it nonetheless moral and why?
Should the others stop him?
Similar cases do happen, for example i read about a situation in Iraq, where a grenade was thrown into the midst of some soldiers and one of them jumped upon it. We might not know the exact motives, but it seems to be the case of killing oneself so others can survive.
What about a mentally ill person, who commits suicide to avoid doing further harm?
E.g. a serial murderer realizes in a short period of clarity, that murder is wrong, that he is capable of tricking the court system and the psychologist to let him out of prison and that he will sometime in the future will forget his realization that murder is wrong and will commit murder again given the opportunity. He then decides not to waste his moment of clarity to commit suicide, so that the chance he will murder further people is reduced to 0.