How to intentionally break/corrupt a sector on an SD card

bad-blocksbad-sectorssd card

I need to test the resilience of some read/write code for some embedded hardware. How might I sacrifice a few SD cards and break several known sectors for a controlled study?

The only thing I can think of is to overwrite a single sector a few million times. I wonder if a Linux badblocks script can be created to run its destructive test on a single sector repeatedly for several hours.

Best Answer

An alternative approach that may be useful.

If your code runs under Linux then maybe you can test it with a "faulty" logical device. dmsetup can create devices that return I/O errors. Just build your device using error and/or flakey target. From man 8 dmsetup:

error
Errors any I/O that goes to this area. Useful for testing or for creating devices with holes in them.

flakey
Creates a similar mapping to the linear target but exhibits unreliable behaviour periodically. Useful for simulating failing devices when testing.

Note: flakey target usage is documented here. Basic example here.

As far as I know an I/O error will be reported immediately, so this is different than real SD card behavior where you can expect delay, stalling etc. Nevertheless I think this approach may be useful in some cases, at least to perform fast preliminary test or so.