We determine the charm and the bottom quark masses $m_c(m_c)$ and $m_b(m_b)$ from QCD sum rules of moments of the vector current correlator calculated in perturbative QCD. Only experimental data for the heavy-quark resonances below the continuum threshold are needed in our approach, while the continuum contribution is determined by requiring self-consistency between various sum rules, including the one for the zeroth moment. Existing data from the continuum region can then be used to constraint the theoretical
error providing a suitable parameterization of such continuum region. Our result is $m_c(m_c) = 1272 \pm 8$ MeV and $m_b(m_b) = 4180 \pm 9$MeV for $\alpha_s(M_z) = 0.1182$. As a byproduct, the parameterization of the $R(s)$ function and the heavy-quark masses are used to determine the contribution of the heavy quarks to the Hadronic Vacuum Polarization contribution to the anomalous magnetic moment of the muon yielding $a_{\mu, LO}^{\rm had, \, charm}= 14.36(23)\times 10^{-10}$ and $a_{\mu, LO}^{\rm had, \, bottom} = 0.30(2) \times 10^{-10}$ respectively.
