3 ms·
Referring to strcpy: > we can only use it if we know our destination buffer is smaller than our source buffer Should be the other way around, surely?
by zabzonk 5y ago
Referring to strcpy:
> we can only use it if we know our destination buffer is smaller than our source buffer
Should be the other way around, surely?
- Randor 5y agoAbsolutely, That's not the only discrepancy. https://pubs.opengroup.org/onlinepubs/9699919799/functions/memccpy.html https://pubs.opengroup.org/onlinepubs/9699919799/functions/m... Note the following: "The memccpy() function does not check for the overflow of the receiving memory area." "If copying takes place between objects that overlap, the behavior is undefined." The strxcpy he provides at the bottom doesn't look better at all. I'm not sure where the author got that function. I found some better variants of the proposed strxcpy function with bounds checks and that provides overflow detection.
- saagarjha 5y agoI wrote strxcpy as an example of a function that satisfies the requirements that I posted at the top. In doing so, it becomes a useful routine for other kinds of needs, such as this one: https://news.ycombinator.com/item?id=27564004 https://news.ycombinator.com/item?id=27564004 The reason I omitted the specific verbiage you quoted is that they apply equally to all the functions. My function has an important bounds check, but (like all of C) trusts that the parameters you provide to it are correct. There is no additional checking done because doing so in C is not tenable. If implemented in a standard library it may be useful to add additional heuristics to detect invalid cases, but they are fundamentally best-effort and not worth showing in an example.
- saagarjha 5y agoLOL yes, thanks for catching that. I’ll fix it when I’m at my computer :) Edit: edited. I also had a messaging from past me that I had forgotten about: <!-- I made a mistake somewhere, didn't I? -->