user1998844
user1998844

Reputation: 467

Why strstr() search for null string always return true?

Why does the strstr function always return true for the following code:

void main(){
    char* a = "qweqweqweqweqweqw";
    char b[5] = {0x00,0xff,0xaa,0xbb,0xcc};
    printf("%p",strstr(a,b));
}

When I replace the null string 0x00 to something else the error goes away. Please help me to understand why?

Upvotes: 3

Views: 5624

Answers (3)

Ctx
Ctx

Reputation: 18410

Many platforms have the function memmem:

void main(){
  char* a = "qweqweqweqweqweqw";
  char b[5] = {0x00,0xff,0xaa,0xbb,0xcc};
  printf("%p", memmem(a,strlen(a), b, sizeof(b)));
}

Upvotes: 1

cadaniluk
cadaniluk

Reputation: 15229

From strstr:

char *strstr(const char *haystack, const char *needle);

The strstr() function finds the first occurrence of the substring needle in the string haystack.

Since strings are null-terminated in C and 0x00 denotes a null byte, b is effectively "".
Searching for an empty string always yields true, so your program will always find the substring.

strstris designed for strings. No string contains 0x00 as a character, so strstrwill not work here. You'll need to write a custom search function like binbin, which seeks binary data in binary data. The function signature might be like this:

unsigned char* binbin(const unsigned char* haystack, size_t haystack_len,
const unsigned char* needle, size_t needle_len);

A size is passed here because we cannot null-terminate the data.

Upvotes: 5

Magisch
Magisch

Reputation: 7352

by putting 0x00 on the beginning of your string b, you essentially created a null-string, since it is terminated in the very first char. you see 0x00 or '\0' is a string terminator, indicating the end of a string for all c string functions. So strstr() reads only the first char, assumes the string ends there, and since there was nothing there before that, assumes the string is a null-string, and a null string is part of every single string there is.

Upvotes: 2

Related Questions