Don't go further and pop the stack if it's empty.

Change-Id: I27bd30ca65cf0066cd022b4b060757913ea01fed
(cherry picked from commit 3ede68e1cc879e6adbf6336eccaf88ced974b8b6)
Check for empty() before calling top().

Else it might crash sometimes.

Change-Id: I6a24fff83c3d36346debae5c0f2b8c0646a15c01
(cherry picked from commit 3f177756dbdb67d901453000c3f11694770d2761)