Wednesday, September 21, 2011

Clobbering a memory leak

I spent today dealing with a subtle bug that had me slogging through code trying to figure out why my application was running out of memory. Adding more memory allowed the program to run longer, so I suspected a (relatively) slow leak. I added reference counters to ensure that every allocation had a matching free, and the reference counters did not indicate any memory regions were being lost. I should not have been exhausting the available memory, and yet I was.

By checking the return value of free I was able to determine that I was passing free an invalid pointer to a location not on the heap. But I was passing it a pointer to an object I allocated! Something was corrupting the pointer.

Normally I would suspect a stack overflow, but since I was using some inline assembly macros nearby I double-checked them. Sure enough I had forgotten to list one of the clobber registers in one of the macros so the compiler did not know that I was using that register. The register was assigned to hold the argument to free but was overwritten by the assembly code causing the original pointer to be silently leaked. By adding the correct register to the clobber list I fixed the memory leak.

Tuesday, September 20, 2011

OT: Gas Psychology

xkcd points out that the cost of saving money on gas in the time it takes to drive out of your way will rarely be worthwhile. The alt text goes further to state that if you drive an average car more than a mile out of the way for each penny per gallon saved you are spending more on gas than you are saving. I was intrigued so I did a little number crunching.

Suppose I can get gas for $4.00 per gallon without going out of my way, and that I usually get 10 gallons of gas. Results will fluctuate depending on the base price and the amount of gas purchased. Here is a chart showing the farthest I can drive before I start to lose money.

Max distance to travel before losing money. Each line represents a different average miles per gallon from 10 m.p.g. to 50 m.p.g.

Taking a vertical slice out of the middle we can see how far to drive when the gas prices are 10 cents apart:
Max distance to save 10 cents per gallon
I also noticed that (at 10 gallons of gas and with $4.00 base) the alt text is correct for vehicles that get up to 40 mpg. At 40 mpg the break-even point is almost exactly 1 mile of travel for each penny per gallon saved. For my car, which gets about 20 to 25 mpg, the break-even point is about 1/2 mile for every penny saved.