开发者

differences between memchr() and strchr()

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 开发者_Go百科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.


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜