lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Ranier:
On Mon, Nov 16, 2020 at 5:03 PM Ranier Vilela <ranier.vf@gmail.com> wrote:
> strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.

No. Strcmp compares strings, a string MUST have a null ( otherwise it
is a char array, but not a string ) so it only has to read, test for
\0 and compare. OTOH strncmp also needs strings, but apart from the
stuff done by strcmp it has to check the count to see wheter it is
done.

> Problem with strcmp function is that if both of the strings passed in the argument is not terminated by null-character, then comparison of characters continues till the system crashes. But with strncmp function we can limit the comparison with num parameter."

If one of them is not terminated by a \0, they are not strings. This
may be due to a previous bug or to sloppy programing, such as not
properly handling your input lengths bounday cases. This would be
probably one of the "undefined behaviour" pitfalls ( I've worked for
more than a decade with C implementations where strcmp did not crash
on a missing null, it just infinite looped some times ).

The fact that some people use strncmp to compare things which may not
be proper C strings is another. If you have something like Pascal
strings you can do that, or you can use just plain memcmp or another
tactic.

Francisco Olarte.