There are a few situations when officers can search your vehicle. The 1st situation is if you give consent/permission to search your vehicle. If the officer asks to search your vehicle, your person or a bag that you have and you give consent/permission then they have a right to search and you can be charged with any illegal items that they find.
The 2nd situation is if they have probable cause to search. Probable cause can be established in several ways. One way is if they see drugs, drug paraphernalia, a weapon, an open container or other evidence of a crime. It can also be established if they smell marijuana or alcohol.
A 3rd way it can be established is through a warrant. If the police have a search warrant for your vehicle, they can search it without your consent.
A 4th way is search incident to arrest. This means that if you are arrested during the traffic stop the officers can search the car after you have been taken into custody to look for further evidence of the crime. Also, if you are arrested and your car is towed or seized officers will typically inventory the car which is another way they can search the vehicle.
Do not consent to a search if you do not want your vehicle searched. Once you consent you have essentially waived your right to challenge the search once the case goes to court.