What is the actual difference between memchr()
and strchr()
, besides the extra parameter? When do you use one or the other one? and would there be a better outcome performance replacing strchr()
by memchr()
if parsing a big file (theoretically speaking)?
strchr
stops when it hits a null character but memchr
does not; this is why the former does not need a length parameter but the latter does.
Functionally there is no difference in that they both scan an array / pointer for a provided value. The memchr
version just takes an extra parameter because it needs to know the length of the provided pointer. The strchr
version can avoid this because it can use strlen
to calculate the length of the string.
Differences can popup if you attempt to use a char*
which stores binary data with strchr
as it potentially won't see the full length of the string. This is true of pretty much any char*
with binary data and a str*
function. For non-binary data though they are virtually the same function.
You can actually code up strchr
in terms of memchr
fairly easily
const char* strchr(const char* pStr, char value) {
return (const char*)memchr(pStr, value, strlen(pStr)+1);
}
The +1
is necessary here because strchr
can be used to find the null terminator in the string. This is definitely not an optimal implementation because it walks the memory twice. But it does serve to demonstrate how close the two are in functionality.
strchr
expects that the first parameter is null-terminated, and hence doesn't require a length parameter.
memchr
works similarly but doesn't expect that the memory block is null-terminated, so you may be searching for a \0
character successfully.
No real difference, just that strchr()
assumes it is looking through a null-terminated string (so that determines the size).
memchr()
simply looks for the given value up to the size passed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With