How to use the new counted_by attribute in C (and Linux)
people.kernel.org
people.kernel.org
> One crucial requirement is that the counter must be initialized before the first reference to the flexible-array member. Another requirement is that the array must always contain at least as many elements as indicated by the counter.
This means as the array is initialized and updated, you must keep the counter updated with it. Its just as easy to screw that up than it is to screw up the general problem of accessing elements that are out-of-bounds
So, while you still have to make sure your structure is sane, now the runtime can play along too.
[1] https://learn.microsoft.com/en-us/cpp/code-quality/annotatin...
What it helps with is fortified builds, as now the compiler/libc can now get an upper bound on the intended size, whereas before it's had to just assume flexible array members are infinitely-long and thus is largely never able to add bounds checking.
The goal of annotations like this is to 1: make it harder to make the mistakes in the first place (by making it possible for the compiler to detect failures to update, etc) and 2: make it possible for the compiler to actually prevent errors even at runtime.
Again the issue is not what happens when everything is perfect, it’s what happens when everything is not.
[edit: I don’t even think you can reasonably call this syntactic sugar as it does not do any of the actual work of updating things for you, it’s literally just telling the compiler what the semantics of the object is, you still have to do everything yourself with the only exception being guaranteed bounds checks which looks to be a compiler mode dependent behavior]