[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.4.2 New assorted suggestions
- From: Sean Conner <sean@...>
- Date: Mon, 16 Nov 2020 05:16:12 -0500
It was thus said that the Great Sean Conner once stated:
>
> And if string comparisons are of such performance important, you might as
> well skip strncmp() entirely (which still has to check for a NUL byte
> anyway) and use a straight memcmp():
>
> if (strcmp(fname, "-") == 0 && memcmp(argv[-1], "--",2) != 0)
Okay, three things wrong here---first off, I'm failed to include the
trailing NUL byte. Second, I missed a strcmp()
if (memcmp(fname,"-",2) == 0 && memcmp(argv[-1],"--",3) != 0)
Third thing, this is *still* wrong in general. Let's take an earlier
example:
if (strcmp(ar.namewhat, "method") == 0) {
If this is changed to memcmp(), as I suggested:
if (memcmp(ar.namewhat,"method",7) == 0) {
If ar.namewhat is shorter than 7 characters (including the NUL byte) then
you run the risk of reading unknown memory, which invokes undefined behavior
in C. I mean, it'll *probably* be okay in practice, but valgrind would
complain bitterly about reading uninitialized memory when testing. You
still need to check for a NUL byte on both strings.
So I rescind my recommendation to use memcmp(). I mean, I got *three*
things wrong in the span of *one* line of C code. There's a reason the code
is written the way it is.
-spc