If sysctl fails with ENOMEM (because the buffer is too small), it will
set length to 0 (what I see) or to the length it actually copied (what
the man page says).
Regardless, this is not the length of the unknown value.
So instead of relying on LEN we tell strncpy the maximum it can
copy. It will add null bytes as necessary if that's too short.
If sysctl succeeded we can use that value.
Now the man page doesn't actually say so, but it seems it copies the
null byte reliably. Still, as I've seen no guarantee let's add a null
byte regardless.
As one last thing the intermediate buffer is unnecessary. It's the same
size as the dynamically allocated anyway and we copy between them. We
can get rid of it and write directly into our buffer.
I think this is mostly theoretical because the buffer is big enough with 20 bytes (currently the version is 7 bytes, e.g. 20.3.0 plus null byte). Still, this is C and thus worth doing correctly.
If sysctl fails with ENOMEM (because the buffer is too small), it will set length to 0 (what I see) or to the length it actually copied (what the man page says). Regardless, this is not the length of the unknown value. So instead of relying on
LEN
we tellstrncpy
the maximum it can copy. It will add null bytes as necessary if that's too short.If sysctl succeeded we can use that value. Now the man page doesn't actually say so, but it seems it copies the null byte reliably. Still, as I've seen no guarantee let's add a null byte regardless.
As one last thing the intermediate buffer is unnecessary. It's the same size as the dynamically allocated anyway and we copy between them. We can get rid of it and write directly into our buffer.
I think this is mostly theoretical because the buffer is big enough with 20 bytes (currently the version is 7 bytes, e.g.
20.3.0
plus null byte). Still, this is C and thus worth doing correctly.