restrictness of strtoi(3bsd) and strtol(3)
Alejandro Colomar
alx at kernel.org
Sun Dec 3 16:33:59 UTC 2023
Hello Amol,
On Sun, Dec 03, 2023 at 09:08:22PM +0530, Amol Surati wrote:
[...]
> Referring to the points you make later, removing the restrict-qualifier from
> nptr then explicitly permits *endptr and nptr to alias, as the types are now
> devoid of restrict-qualifiers.
[...]
> I think I understand. Since strtol is an external function, the compiler, when
> when compiling strtol(p, &p, 0), has enough information, in the form of the
> strtol prototype and a call to it, to warn about the fact that nptr and *endptr
> may alias in a way that triggers an undefined behaviour.
Exactly.
>
> Based on how I understood the latest draft n3096.pdf, it is the write to a
> char through *endptr (along with a read of that char through nptr) that
> triggers the violation of the 'restrict' clause. The read and write need not
> be in a particular order. No major compiler warns, though, as evident by
> an example at https://godbolt.org/z/a4xza5xna
As you say, ISO C's formal definition of restrict permits pointers to
overlapping memory, as long as only one of the pointers is dereferenced.
> ------
> What sort of optimizations can a strtol implementation hope to achieve?
> A couple of libcs discard the restrict qualifier when calling their handlers
> for strtol. The situation with strtol doesn't seem to be similar to that with
> memcpy-memmove.
>
> It seems that, as long as strtol does not assign a value to **endptr, it
> continues to adhere to the std.
To be pedantic, even reading a value from **endptr would cause UB.
But yeah, the point is there: the standard's definition of restrict
isn't very good.
> The historical docs point towards a decision to stamp the prototype with
> restrict under the assumption that (1) the string and the pointer to string
> are in disjoint memory locations,
This justifies the restrict on endptr.
> and (2) the implementations would
> use endptr for nothing else other than maintaining a position in the given
> string.
This is quite brittle. The restrict on ntpr should cause the compiler
to scream. I'll report a missing warning on bugzilla.
Cheers,
Alex
--
<https://www.alejandro-colomar.es/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://lists.freedesktop.org/archives/libbsd/attachments/20231203/dd43c913/attachment.sig>
More information about the libbsd
mailing list