In the responses to the question Reading In A String and comparing it C, more than one person discouraged the use of strcmp()
, saying things like
I also strongly, strongly advise you to get used to using strncmp() now, ... to avoid many problems down the road.
or (in Why does my string comparison fail? )
Make certain you use strncmp and not strcmp. strcmp is profoundly unsafe.
What problems are they alluding to?
The reason scanf()
with string specifiers and gets()
are strongly discouraged is because they almost inevitably lead to buffer overflow vulnerabilities. However, it's not possible to overflow a buffer with strcmp()
, right?
"A buffer overflow, or buffer overrun, is an anomaly where a program, while writing data to a buffer, overruns the buffer's boundary and overwrites adjacent memory."
( -- Wikipedia: buffer overflow).
Since the strcmp() function never writes to any buffer, the strcmp() function cannot cause a buffer overflow, right?
What is the reason people discourage the use of strcmp()
, and recommend strncmp()
instead?
strncmp()
is no better (or worse) thanstrcmp()
. – Rozierstrncmp
to protect against strings which are not null terminated just papers over the root problem which is that you have a non-terminated string. It will just mess up on the next function that assumes it's null-terminated. – Treachery