2

NOTE - This is very similar to restrict qualifier and pointer arithmetic , but is not a duplicate. The author of that post assigned the result of operations on a restrict pointer to the same pointer, while I assigned the result of operations on a restrict pointer as an argument to a restrict function parameter.

I understand the meaning of restrict for the most part, and I'm beginning to get in the habit of declaring function parameters restrict whenever applicable. But I'm unsure whether I'm abusing it here or not.

struct DynArray
{
    void* data;
    size_t elemCount;
    size_t len;
};

void dyn_append(DynArray* restrict dst, const void* restrict src, size_t srcLen, size_t elemSize)
{
    size_t oldElemCount = dst->elemCount;
    dyn_setElemCount(dst, dst->elemCount + srcLen, elemSize);    // might write to `*dst`
    if (dst->data)    // `dst->data` is set to `NULL` if reallocation fails.
        // The next line might violate "restrict-ness" of `dst`.
        memcpy((char*)dst->data + elemSize*oldElemCount, src, elemSize * srcLen);
} 

Specifically, I'm referring to (char*)dst->data + elemSize*oldElemCount in the call to memcpy. If I had passed dst itself rather than the above argument, I know it would be valid, as I would be assigning it to a parameter of a function that is itself restrict. Does the fact that the argument is the result of operations on dst rather than dst itself change things in this case? My reasoning is that the guarantee that the argument won't be aliased is contained within the guarantee that dst won't be aliased.

Isaac Saffold
  • 1,116
  • 1
  • 11
  • 20
  • This code does not assign to any of the function parameters. (Modifying data that a pointer points to, is different to assigning to the pointer) – M.M Dec 15 '18 at 00:41
  • 1
    `dyn_setElemCount` cannot write to `dst` because it is passed by value. If you mean it writes to the memory that `dst` points to , then please update the question to say so. As things stand the question is unclear. – M.M Dec 15 '18 at 00:45
  • 3
    The value of `dst->data` does not inherit the `restrict`-ness of `dst` – M.M Dec 15 '18 at 00:49
  • "Does the fact that the argument is the result of operations on dst rather than dst itself change things in this case?" Depends on if `src` overlaps `dst->data`. – chux - Reinstate Monica Dec 15 '18 at 01:58
  • @M.M I mixed up the local copy of the parameter when it's passed an argument with the parameter itself. Why I didn't just say "passed an argument to the parameter" is beyond me. And yes, I meant the data that it points to. I updated my post. Thank you for pointing that out. – Isaac Saffold Dec 15 '18 at 02:08

1 Answers1

1

This is fine, but it doesn't really do anything because there's no time when aliasing the dst pointer would cause different behavior.

T Percival
  • 8,526
  • 3
  • 43
  • 43