0

I got a block of memory where I need to search for 2 consecutive chars.

I can't use strstr since my block of memory might contain '\0', and memchr only search for a single char. Is there some function similar to strstr, that works for non null-terminated, or should I use memchr followed by a manual check of the next element. Thanks.

Paul R
  • 208,748
  • 37
  • 389
  • 560
monkeyking
  • 6,670
  • 24
  • 61
  • 81
  • 3
    Do you want a C solution or a C++ solution ? – Paul R Mar 11 '12 at 14:06
  • 3
    The GNU C library has a non-standard extension called `memmem` that does this. – Fred Foo Mar 11 '12 at 14:08
  • 3
    http://stackoverflow.com/questions/3280553/memmem-stl-way – Piotr Praszmo Mar 11 '12 at 14:11
  • 1
    possible duplicate of [How to search in a BYTE array for a pattern?](http://stackoverflow.com/questions/7319391/how-to-search-in-a-byte-array-for-a-pattern) or [A pure bytes version of strstr?](http://stackoverflow.com/questions/1992253/a-pure-bytes-version-of-strstr). – Raymond Chen Mar 11 '12 at 15:04
  • 1
    @PaulR Here at stackoverflow, they don't think there is a difference between c and c++. I gave up trying to convince them a long time ago. – Deanie Jan 07 '22 at 23:14

2 Answers2

3
for (p = memstart; p <= (memstart + memsize - stringsize); p++)
{
    if (memcmp(p, string, stringsize) == 0)
    return p; /* found */
}
return NULL; /* not found */

http://www.koders.com/c/fidD66F4C2F1935B0FF6158A83C4FBF134C4432F5CF.aspx

Dan
  • 10,531
  • 2
  • 36
  • 55
2

The C++ way to do this would be:

char* result = std::search_n( mem, mem + size, 2, c );

Where mem is the start of your buffer, size is the size in bytes, and c is the character to search for. search_n should return mem + size if no match is found.