There are generally three conditions under which a police officer can search a car after a traffic stop.
The first of these conditions is the consent of the driver. The police may search anything they wish (house, car, backpack, etc) if the person who is control of that thing has given them permission. Police will often ask permission to search a car. If permission is granted, they may conduct a search after a traffic stop.
The second condition is if the officer has probable cause to believe that they will find evidence of some crime in the car. Probable cause, of course, is somewhat hard to define. The police have to have a good reason to think they will find something, but they do not have to be 100% certain. For example, they cannot search a car because its occupants look suspicious, but they can search it if the occupants fit the general description of suspects in a crime recently committed in the vicinity of the place where the traffic stop occurs.
Finally, the police have the authority to search a car if they have reasonable cause to believe that someone in the car might pose a danger to them. For example, if the police have reasonable cause to believe that someone in the car might have a gun, they can search the car without a warrant.
These are the general rules about when the police can search a car without a warrant after a traffic stop. The exact details of the situation will determine whether the search is actually legal, but these are the general outlines of the situations in which it is legal to conduct such a search.