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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With