Morocco, eliminated after drawing all three matches, were four minutes away from beating the hosts before defender Siyabonga Sangweni levelled.
Issam El Adoua opened the scoring for Morocco in the 10th minute at the Moses Mabhida Stadium.
May Mahlangu pulled South Africa level with a curling shot in the 71st minute only for substitute Abdelilah Hafid to restore Morocco's lead with a breakaway goal 11 minutes later.
South Africa will stay in Durban for their quarter-final against the runners-up in Group B who will be determined on Monday.
- Sports & Recreation