My understanding from TV documentaries (which might be wrong), but before around the 1700s, food preservation was a major issue. Things would simply rot, so had to be eaten fairly soon after gathering and methods like salting could be expensive.
So how did castles feed their garrison for months on end while under siege?
So, it's absolutely untrue that medieval people were incapable of preserving food. I don't know how much you know about agriculture, but plants don't really grow during winter, and medieval agriculture was heavily dependent on grains. If you were a stereotypical peasant, you brought in the winter crops at the beginning of the summer, and the spring crops in late summer and early autumn. In early November you rounded up your pigs and old animals (young stock were sold in the summer) and slaughtered and preserved their meat. This gives a gap of about six months where no significant amounts of food could be produced. If medievals had no skill at preserving food, every winter would have caused mass famine.
Grains like wheat, barley, and rye don't spoil quickly at all. Medieval farmers preserved the things that were in danger of spoiling with drying, smoking, and salting/brining (salt was certainly in demand and thus rather dear, but that doesn't mean it wasn't essential to the diet). So the foods that are being preserved may be fairly bland - they're things like ham, bacon, and sausages, beer/wine, dried beans and peas, salt fish - but there's no problem making some kinds of food last. Since most medieval castles were in the countryside and supplied by these people, it's probable that you would find much the same variety of food in their larders.
But it was also quite rare that a siege would last for "months on end." The vast majority of castles were small and weakly defended local fortifications that were vulnerable to any large, determined besieging force. A pro forma surrender after a few days of honorable resistance was a more common result than either an assault or a prolonged siege. Those castles which did resist siege for months at a stretch were usually the larger, better prepared royal or comital castles that had major strategic value, and offhand I can't think of one that made it more than eight months.
Chronicle accounts of the civilian experience of siege warfare are a tempermental historical source in some ways. Writers drew heavily on a literary tradition of several famous siege accounts--notably Josephus' account of the siege of the 70 CE Jerusalem (known in the later Middle Ages especially through Jacobus de Voraigne's Legenda aurea) and its own referrent, the siege of Samaria recorded in 2 Kings. So some patterns of civilian desperation are hard to balance between reality and literary topos.
That's one of the things that makes the pipe roll ledger from the brief siege of Nottingham in 12C so valuable. It tells us that after Richard retook the castle from the wayward future king John, the castle's siege-ready provisions were sold off: corn (in medieval use, this is "grain" rather than maize), beans, peas, salt pork (slab bacon), cheese. Contemporary records from Bristol suggest the same type of storing up provisioning: beans, peas, wheat, wine.
Medieval people, it seems, were fairly well versed in at least trying to set aside food. It's common in siege accounts to hear of a castle's military garrison having sufficient supplies for the long haul, only to be burdened by refugee civilians they hadn't counted on feeding. And William Chester Jordan argues based on chronicle accounts that the first year of the 1315-1322 Great Famine doesn't seem to have bothered people particularly, because they had enough food set aside to weather a brief interruption in food provisioning. Where people had space for gardens, they could grow their own vegetables to supplement purchased grains and meat (so long as they did not get desperate enough to eat seeds before planting).
Nevertheless, there were definite difficulties: English ordinances and account books are sprinkled with references to selling off wheat stores that seem to be spoiled, and even offloading rotting salted meat (pork or fish) to local religious houses. And a persistent problem in times of siege was access to local mills. If the mill was outside town walls (if there were town walls in the first place, a problem that suddenly confronted northern France in the Hundred Years' War!), grain could not be ground into flour for bread! Apparently making soggy grain-porridge or using handmills was an undesirable option: the town of Dinkelsbuhl paid handsomely to have its mill protected in the 14C.
Particularly in Iberia, where town siegecraft played a key role in the back-and-forth waves of the "Reconquista," expanding town walls to protect key local resources involved something else food-related: livestock and pasture. The heavily-pastoral economy of a lot of the peninsular interior meant a town's herds were its economic livelihood as well as basic sustenance. So it was critical to have space for the animals and at least some natural food for them, as well.
There were also several strategic ways of stretching existing food provisions as long as possible, tactics that opposing armies frequently tried to combat. First, medieval towns under siege were not terrible at obtaining new provisions even during sieges. Byzantine generals on the front lines against various Muslim empires in the east complain about local Christian rural populations selling food to the garrison of Muslim-held castles. This is actually one reason that scorched-earth campaigns of local territory, such as the defenders of Rouen attempted during the Hundred Years' War, were somewhat atypical as defensive tactics despite the besiegers' need for sustenance from the same land. (Bert Hall wonderfully points out that disposal of horse excrement was often a bigger problem for armies laying siege than obtaining new human and horse food, anyway).
Plenty of cities and castles under siege sent letters to their king or lord begging for relief from siege-famine. If help was going to come, it was useful to have a river. The Seine, for example, saved Paris from starvation under a Burgundian siege force in the 15th century; on the other hand, Edward III's successful blockade of the Seine contributing greatly to starving out Calais during the 100YW.
Another, often tragic, means of stretching supplies had nothing to do with preservation or augmentation. Rather, it involved reducing the number of people to feed. At Chateau Gaillard/Les Andelys in early 13C and Rouen in 15C, military commanders made the awful, heart-wrenching decision to expel militarily-less-useful civilians who had taken refuge (Gaillard) or remaind (Rouen) at the onset of local hostilities. In both cases, civilians were expelled in waves. In both cases, the initial group was let through the siege lanes of the attackers, at great cost to whatever goods they had taken with them and, in the case of women, sexual assault.
But Christian charity couldn't win out against utilitarian warfare. In both cases, attacking commanders had to order that the final groups of civilians be turned back. They found the doors to their former refuge locked against them, too. And so we hear of the old, the sick, the young, desperately digging ditches outside the walls of Gaillard and Rouen in Normandy winters, scrabbling to eat grubs and rotting horse carcasses.
So when we hear about accounts of people in cities reduced to paying exorbitant prices for dog meat, rat meat, cat meat, mouse meat, horse meat ("lean or fat"), as sieges stretched on and on--remember that those were the lucky ones.
I'm most familiar with the medieval period, so I'll talk about castle supply in the 14th and early 15th centuries.
In the The Book of Deeds of Arms and of Chivalry, Christine de Pizan goes into great detail about the victualling of a fortress prior to a siege. While I strongly suspect that there has been some scribal error in the manuscript or else that de Pizan mistook the daily requirements of wheat for the men and grain for their horses for the six month period, she does provide a marvelous list of what foods a garrison would have access to during a siege. These are:
Wheat (one third as bread, presumably double baked, and eleven percent as ready to use flour)
Beans
Peas
Wine
Salted and fresh (read: still living) meat in the form of beef, pork and lamb
Salted and dried fish
Salted butter
Poultry (live)
There are other minor stores, such as spices, ten pounds of rice, etc, but these are the main foodstuffs she recommends. Interestingly, she makes no reference to cheese, though it was clearly a part of mid-14th century English campaign supplies.
What stands out is that all this is that all the foods are long lasting. The meats are either salted/dried, and so preserved, or else the animals are kept live inside the castle and slaughtered at need. The butter is similarly salted so as to preserve it, and the wheat, beans, peas and wine will last a considerable time. Wastage of wheat, if properly winnowed and in a dry, pest free environment will typically be below 10% per year, and I imagine that the legumes will have a similar wastage.
The key is really good storage conditions for the grain and the use of salt, drying or some other curing process on the meats. The butter can be salted to enhance its life, and the cheese generally kept well in any case, given the right conditions.
Sources
The Book of Deeds of Arms and of Chivalry, by Christine de Pizan, tr. Summer Willard
The Organisation of War Under Edward III, by H. J. Hewitt
Experimental Archaeology at L'Esquerda – Crops, Storage, Metalcraft and Earthworks in Mediaeval and Ancient Times, by Imma Ollich, Montserrat de Rocafiguera, Maria Ocaña, Carme Cubero and Oriol Amblàs
Risk, Transaction Costs, and the Organization of Medieval Agriculture, by Stefano Fenoaltea