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

Discussion in 'C Programming' started by Dan Pop, Jul 24, 2003.

  1. Dan Pop

    Dan Pop Guest

    In <bfocbv$gepau$-berlin.de> 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:
     
    Dan Pop, Jul 24, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. crjunk
    Replies:
    2
    Views:
    16,916
    crjunk
    Aug 8, 2003
  2. Joona I Palaste

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

    Joona I Palaste, Jul 24, 2003, in forum: C Programming
    Replies:
    0
    Views:
    442
    Joona I Palaste
    Jul 24, 2003
  3. Thomas Matthews

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

    Thomas Matthews, Jul 24, 2003, in forum: C Programming
    Replies:
    0
    Views:
    541
    Thomas Matthews
    Jul 24, 2003
  4. Burne C
    Replies:
    3
    Views:
    1,363
    Peter Ammon
    Jul 25, 2003
  5. Paul Butcher
    Replies:
    12
    Views:
    787
    Gary Wright
    Nov 28, 2007
Loading...

Share This Page