Moubarak Boussoufa’s 90th-minute strike for Morocco left South Africa’s hopes of reaching the knockout stages of the Africa Cup of Nations hanging by a thread.
In a game of few chances, Boussoufa’s instinctive finish settled the contest in Cairo on Tuesday and sealed Morocco position at the top of Group D.
Achraf Hakimi smacked the crossbar after driving in from his left-back position to bend a right-foot shot onto the woodwork shortly after the hour-mark.
But Boussoufa scrambled in the winner in the final minute of normal time as South Africa failed to clear a corner and hooked his shot from close range over the line.
Morocco go through as Group D winners with nine points from their three games, while Ivory Coast sealed second spot in Group D after a convincing 4-1 win over bottom-placed Namibia.
Bafana Bafana rarely threatened to find a breath-through themselves, and with just three points from their three group games, they must wait to find out if that is enough to reach the round of 16.
The four best third-placed teams will progress, with Guinea confirmed having taken four points from their three games. DR Congo and Kenya are also on three points, while Benin and Angola have two points with one game remaining.