How should I fill the gap between window trim and walls?
You will want to clean the area first.  Scrape and moderately sand any peeling paint.  Afterwards use a latex caulking which you can find at any home improvement store.  This caulking is paintable which is the main reason I would use it and also shrinks and expands with temperature and moisture changes.  Once the caulk is completely cured according to the directions on the tube, you can paint over the area.  The better caulk products tend to have more flex giving them better longevity and decreases there chance of pulling away from the wood/molding.

Also, one more thing to add;  What is the cause for the cracking in the first place?  You may get more cracking if there is insufficient insulation between the rough opening and the window frame.  Usually this can be solved easily by spraying foam insulation in between the two.  This would be a more time consuming and difficult task, but may solve the root cause since this type of foam both insulates and seals the gap eliminating moisture and decreasing temperature change, both common causes of major expansion around windows and doors.  The process for this fix would start with removing your trim, insulating with the foam, re-installing your trim and then following the steps above.  This may not be worth the work depending on where you live, etc.... but it is a notable option.