The gravitational potential energy of a mass at a point in a field is defined as the work done by an external agent in bringing that mass from infinity to that point, without a change in kinetic energy.
So, assume that we are applying a force away from the body's gravitational field (to keep acceleration or KE zero) and the displacement is towards the body. The potential energy at infinity, $U_\infty = 0$.
$dw = F \cdot dr$
$\int_{W_\infty}^{W_r} dw = \int_\infty^r F\,dx\, cos\theta$
$\int_{W_\infty}^{W_r} dw = \int_\infty^r F\,dx\, cos180^\circ$
$\int_{W_\infty}^{W_r} dw = -\int_\infty^r \frac{GMm}{x^2}\,dx\qquad$(since, $cos180^\circ = -1$)
$\int_{W_\infty}^{W_r} dw = -GMm\, [\frac{-1}{x}]_\infty^r$
$\int_{W_\infty}^{W_r} dw = -GMm\, [\frac{-1}{r} + \frac{1}{\infty}]$
$U_r - U_\infty = \frac{GMm}{r} \qquad$ (since the work done by external force = potential energy and $\frac{1}{\infty} \rightarrow0$)
$U_r = \frac{GMm}{r}$
But the correct expression for it is $U_r = \frac{-GMm}{r}$
Why is this wrong?
I know this can also be derived by bringing the mass from $r$ to $\infty$, but why this doesn't work?