Cache can only mask performance. It can't mask fraudulent reporting of storage capacity. At worst, the test above will return (size of write cache + size of actual storage), but a bargain-bin flash drive is going to have a very small (if any) write cache, so it's not going to overestimate by much.
Sure, so if the drive is genuine, or even one sector short (I recognize it's more typically a much larger fraction for the fraudulent drives), you'd still have to write to nearly the full stated capacity to verify.
This approach though, seems to require reading the first sector many times.
If it is genuine your quadratic version will perform the same number of writes as the linear time solution.
If it is non-genuine what do you care how many writes it will perform? In that case the media is trash anyways.
The quadratic test will take an eternity due to the n^2 hashing operations and reads unless it terminates extremely early.
If you really have a need to terminate writing early, you could at least perform only a few reads randomly after each write (which will terminate early with high probably not long after you reached the maximum).
write 0001, read and confirm, repeat until drive is full.
For a fake drive, it'll take awhile, because the underlying storage is much, much slower than it should be, often usb2 speeds.
Realistically, this is just a test that satisfies curiosity without opening the drive. It's obvious when you have a fake drive because it won't benchmark anywhere near what it should.
The problem is the fake storage can just overwrite the new data on top existing data. Then you always confirm new data is correct because it broke the old ones.
But something like 2TB micro SD when actually it only has 64GB capacity, that will be very long time waiting 2TB to fully written.
How about write some file, then verify sometimes the new sometimes the old one, repeat until full.
"it only writes what’s necessary to test the drive"
How does that actually work, wouldn't that mean the whole stated capacity would have to be written?