Jay
Jay

Reputation: 24905

What happens if I pass a non-null terminated buffer as the first argument to strstr?

As I understand, the function char *strstr(const char *s1, const char *s2); searches for the null terminated string s2 in the null terminated string s1.

Let's say, I pass a null terminated string s2, but the buffer passed as s1 is not null terminated, what will happen in such a case if the string s2 is not present in s1? The function strstr will keep searching for s2 beginning from the start address of s1, till it finds some '\0'. But, let's say it doesn't find a '\0' at all? Will it access some protected or prohibited memory area and crash?

I know this is an undefined behavior, but based on your experiences, what could be the problem?

Upvotes: 1

Views: 2866

Answers (1)

user529758
user529758

Reputation:

I know this is an undefined behavior

And here ends your question. Because it is UB, nobody can tell you what will happen for sure. Yes, it may cause an access violation and dump core. It may accidentally encounter a 0 somewhere in the memory and stop there. It may find the substring as well (small chance). Or it may cause demons to fly out of your nose.

Upvotes: 8

Related Questions