In a single-pilot aircraft like the C172 there are basically two scenarios. The key difference between the two is: who is acting as PIC? As background, keep in mind the following:
- Acting as PIC and logging PIC are two different things
- Per 91.109(c), a safety pilot is required for simulated instrument flight
- 14 CFR 61.51 has the complete rules on logging PIC and SIC time
Scenario 1: the safety pilot acts as PIC
In this scenario, the safety pilot (SP) acts as PIC while the pilot flying (PF) actually controls the aircraft. That means the SP can log PIC time per 61.51(e)(iii) because they are acting as (emphasis mine):
[...] pilot in command of an aircraft for which more than one pilot is
required under the type certification of the aircraft or the
regulations under which the flight is conducted
Meanwhile, the PF can also log PIC time per 61.51(e)(i) as long as they are the "sole manipulator of the controls", i.e. they are actually flying the aircraft.
Scenario 2: the pilot flying acts as PIC
Here, the SP cannot log PIC time. They are not acting as PIC, nor are they the sole manipulator of the controls. However, they are still a required crewmember per 91.109, so they can log SIC time per 61.51(f)(2). The PF can log PIC time as the sole manipulator of the controls.
In practice1, what usually happens is that the pilots agree that the SP will act as PIC. The reason is that it allows both pilots to log PIC time, which is usually desirable for both of them. But that means the SP must be authorized to act as PIC, i.e. valid medical, qualified to act as PIC for the aircraft type, current etc. If the SP is qualified to be a safety pilot but not PIC, then only scenario 2 above is possible.
We have a lot of questions on this site about logging PIC time in various scenarios, so please search and review them carefully before asking a new question that may already have been answered.
1 What really happens most of the time in practice is that the pilots don't discuss any of this and they just both log PIC time for the flight. That's not ideal, but if something goes wrong the FAA will ask "so, who was acting as PIC?". If the pilots can't answer that clearly, things probably won't go so well for either of them. And if the SP logged PIC time without being qualified to do so, it's likely to go even worse.