Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 696
user1998844 Avatar asked Mar 05 '26 15:03

user1998844


1 Answers

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.

like image 75
cadaniluk Avatar answered Mar 08 '26 07:03

cadaniluk