Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Re: memcmp versus strstr; reaction to chr(0)

Reply
Thread Tools

Re: memcmp versus strstr; reaction to chr(0)

 
 
Dan Pop
Guest
Posts: n/a
 
      07-24-2003
In <bfocbv$gepau$> Walter Dnes <> writes:

> When I asked in another thread about string comparisons, I forgot
>about the chr(0) booby-trap in C strings.


It's not a booby-trap, it's a string terminator

>Since I want to compare
>random binary data, this is important to me. Someone correct me if I'm
>wrong; strstr stops at chr(0).


All the functions whose names start with str stop at the end of the
string.

>memcmp doesn't treat chr(0) as a
>delimiter, and can compare ranges (the word "strings" is incorrect here)
>that included embedded chr(0).


memcmp (like all the other functions whose names start with mem)
operates on memory blocks defined by their start address and length.

>I realize that memcmp won't
>automatically scan a larger string, but I can put it in a loop to sweep
>through a larger string.


I don't get you. memcmp will scan a memory block as large as specified
in its third argument.

>Too bad that memmem is not standard.


It's trivial to implement, using memchr and memcmp:

#include <string.h>

void *mymemmem(const void *s1, size_t n1, const void *s2, size_t n2)
{
const unsigned char *p, *p1 = s1, *p2 = s2;

if (n1 == 0 || n2 == 0) return NULL;
while ((p = memchr(p1, *p2, n1)) != NULL) {
n1 -= p - p1;
p1 = p;
if (n1 < n2) break;
if (memcmp(p1, p2, n2) == 0) return (void *)p1;
p1++;
n1--;
if (n1 < n2) break;
}
return NULL;
}

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Mozilla versus IE versus Opera versus Safari Peter Potamus the Purple Hippo Firefox 0 05-08-2008 12:56 PM
equal? versus eql? versus == versus === verus <=> Paul Butcher Ruby 12 11-28-2007 06:06 AM
Re: memcmp versus strstr; reaction to chr(0) Burne C C Programming 3 07-25-2003 06:21 PM
Re: memcmp versus strstr; reaction to chr(0) Thomas Matthews C Programming 0 07-24-2003 02:34 PM
Re: memcmp versus strstr; reaction to chr(0) Joona I Palaste C Programming 0 07-24-2003 10:37 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57