The number of sections is used in assignAddresses (in finalizeAddresses) and the space for all sections is permanent from that point on, even if we later decide we won't write some of them.
The VirtualSize field also gets calculated in assignAddresses, so we need to manually check whether the section is empty here instead.
It feels like S->getVirtualSize() should return 0 if all sections in it are empty. Can you fix the code computing output section size instead of computing a bogus value as a size and then remove such section here?