Answer
Mg metal has a greater $E^{\circ}_{red}$ value as compared to the metal of pipe (iron, etc). Hence it corrodes on the surface to form MgO, which can not be further corroded and acts as a shield for the pipe. Hence the Mg is called sacrificial metal, as it sacrifices itself to protect the metal of pipe (Mg we are obliged to you).
Work Step by Step
Given above