Hello,
Let `struct Buffer` be defined as:
-a struct Buffer { unsigned char *bytes; size_t length; };
Then let's define the following function:
-a int buffer_append(struct Buffer *dst, const struct Buffer *src)
-a {
-a-a-a // checks on size etc etc, return non-zero on failure
-a-a-a memcpy(dst->bytes, src->bytes, length);
-a-a-a dst->bytes += length;
-a-a-a dst->length -= length;
-a-a-a return 0;
-a }
In my understanding, if we call buffer_append(&x, &y) for x.bytes and
y.bytes pointing to overlapping areas of the same array, we get UB by
the first two parameters of memcpy being restrict-qualified pointers.
I suppose the correct thing to do would be to replace memcpy with
memmove, allegedly taking some performance penalty.
Assuming that such penalty matters on the scale of things, what is
the correct/recommended way of handing this situation?
Use memmove.-a Your assumption about the performance penalty is
unwarranted - it should be negligible on any scale of things.-a And even
if the performance penalty was big, "correct" is better than "fast"
every time.
You have a very strange definition for your "Buffer" type.-a A "Buffer"
type that does not keep track of the start of the buffer, but only the
end point and the space remaining in the memory allocation, is not much
use as a buffer.-a It might be useful as a "Buffer_End_Point" type, but
not "Buffer".
In my understanding, if we call buffer_append(&x, &y) for x.bytes and
y.bytes pointing to overlapping areas of the same array, we get UB by
the first two parameters of memcpy being restrict-qualified pointers.
implications in the absence of restrict. Various ways of implemeting a memcpy-like function will produce various unexpected results when
objects overlap, even without any undefined behavior taking place. For instance if we copy byte-by-byte, from lowest address to highest, then
we end up writing into memory that our loop is about to read from,
corrupting the data.
| Sysop: | Amessyroom |
|---|---|
| Location: | Fayetteville, NC |
| Users: | 54 |
| Nodes: | 6 (0 / 6) |
| Uptime: | 17:39:31 |
| Calls: | 742 |
| Files: | 1,218 |
| D/L today: |
4 files (8,203K bytes) |
| Messages: | 184,414 |
| Posted today: | 1 |