Reputation: 241
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)?
Upvotes: 24
Views: 15220
Reputation: 754843
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.
Upvotes: 11
Reputation: 7832
In practical terms, there's not much difference. Also, implementations are free to make one function faster than the other.
The real difference comes from context. If you're dealing with strings, then use strchr()
. If you have a finite-size, non-terminated buffer, then use memchr()
. If you want to search a finite-size subset of a string, then use memchr()
.
Upvotes: -1
Reputation: 10482
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.
Upvotes: 1
Reputation: 241651
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.
Upvotes: 17
Reputation: 43508
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.
Upvotes: 2