Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between memchr() and strchr()

Tags:

c

char

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)?

like image 267
Jun1o Avatar asked Nov 23 '10 19:11

Jun1o


4 Answers

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.

like image 157
jason Avatar answered Nov 13 '22 22:11

jason


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.

like image 25
JaredPar Avatar answered Nov 13 '22 22:11

JaredPar


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.

like image 2
Blagovest Buyukliev Avatar answered Nov 13 '22 20:11

Blagovest Buyukliev


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.

like image 1
Gavin H Avatar answered Nov 13 '22 22:11

Gavin H