I have the following code to implement my own version of string search in C. The string search function returns a pointer to the first occurrence in haystack of any of the entire sequence of characters specified in needle, or a null pointer if the sequence is not present in haystack. This is my code:
char *
mystrstr(const char *haystack, const char *needle)
{
size_t length = 0;
size_t i = 0;
size_t j = 0;
const char *p1;
const char *p2;
p1 = haystack;
p2 = needle;
assert(haystack != NULL && needle != NULL);
while (needle[length] != '\0') {
length++;
}
while (*p1 != '\0') {
p2 = needle;
j = 0;
while (j < length && *p1 == *p2) {
p1++;
p2++;
j++;
}
if (j == length) {
return i;
}
p1 = p1 - j + 1;
i++;
}
return NULL;
}
However, when I test this code, I get an error message saying that it cannot access the memory. Any ideas on what might be the issue here? Also any suggestions on how to improve the code to make it mimic the function as described above?
change
to