The problem of the stability of magnetic fields in stars has a long history and has been investigated in detail in perturbation theory. Here, we consider the nonlinear evolution of a nonrotating neutron star with a purely poloidal magnetic field, in general relativity. We find that an instability develops in the region of the closed magnetic field lines and over an Alfvén timescale, as predicted by perturbation theory. After the initial unstable growth, our evolutions show that a toroidal magnetic field component is generated, which increases until it is locally comparable in strength with the poloidal one. On longer timescales the system relaxes to a new non-axisymmetric configuration with a reorganization of the stellar structure and large-amplitude oscillations, mostly in the fundamental mode. We discuss the energies involved in the instability and the impact they may have on the phenomenology of magnetar flares and on their detectability through gravitational-wave emission.