See below.
When the null byte of the null-terminated input string is encountered, the first loop exits and the next loop begins.
This next loop pops characters (contained in full words) off of the stack until the null at the bottom of the stack is encountered. Each character popped off the stack is placed into the string buffer, overwriting the character originally there.
The null at the end of the input string is not overwritten. It will remain there as part of the null-terminated result string.
You know the drill: fill in those blanks.