This is an example of cathodic protection. Magnesium is more reactive than the iron/steel of the ship's hull. It acts as a sacrificial anode, corroding preferentially and thus protecting the ship from rusting.