Why does UDP have a length field in the header and TCP does not?
I am guessing that the length of the segment in TCP is inferred from the IP header but one should be abl
It's just the way UDP was originally specified. UDP could work without a length field in the header in the same way TCP does.
How is the length of each segment obtained in TCP? It is really up to the specific implementation (OS). The RFC for TCP just states:
Any lower level protocol will have to provide the source address, destination address, and protocol fields, and some way to determine the "TCP length", [...]