Hacker News new | ask | show | jobs
by dataflow 1939 days ago
I actually ran into a case where I wanted to do this, but was forced not to.

What was the scenario? I had a couple of small, fixed-size char buffers and I wanted to swap their valid portions, but the obvious choice of swap_ranges(a, b, a + max(na, nb)) would run into this issue. (n.b. this wouldn't be correct for non-POD types anyway, but we're talking about chars.)

On top of it being annoying to not be able to do the convenient thing, it made life harder when debugging, because the "correct" solution does not preservs the bit patterns (0xCC/0xCD or whatever) that the debug build injects into uninitialized arrays, therefore making it harder to tell when I later read an uninitialized element from a swapped-from array.

1 comments

Why would you ever want to swap an uninitialized value into a buffer? You're wasting CPU cycles writing out data that you are guaranteed to never want to use. Why not just do a copy from the source buffer to the uninitialized one (as that is likely the half of the swap that is desired)?
I literally explained why I want to do that in my last paragraph?
Your last comment just talks about not detecting when you read uninitialized values, but obviously, you wouldn't read uninitialized values _if you never wrote them_?

Unless your use case is swapping with an uninitialized buffer to mark a buffer as "done" and detect further use of it?

You're not understanding what I'm saying. I'm talking about what I see in the debugger when I'm debugging. When you see 0xCC in a variable in the debugger you know you probably had an out of bounds read. Because in debug mode the compiler and runtime leave these markers in uninitialized memory. For that to be helpful you need to swap until the max of the initialized sizes of both arrays, so that you preserve these markers. You defeat that helpful feature if you copy the uninitialized portion of the buffer instead of swapping.
Oh I think I see, I never considered the scenario where the buffer was half uninitialized, I thought you meant you were swapping an (entirely) uninitialized buffer with an initialized one.
Well that certainly could be a special case of the more general scenario I wrote; that's what would happen if it turned out the first buffer had nothing useful in it and the second one was full. But yeah, in general they'd both be partially filled: you have [0, ?, ?] and [1, 1, ?] and want to swap them. You wouldn't touch the last ? in either, but you would swap the [0, ?] with [1, 1], and in debug mode you'd see ? = 0xCC. Except the language doesn't really let you do that, even though fundamentally there should be nothing wrong with it, and in fact is likely to be desirable in practice.