Search code examples
crestrict-qualifier

Does this violate the semantics of `restrict`?


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.


Solution

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