Here is the full code
int count_substr(const char *str, const char *sub)
{
char *ret;
int a = 0; // used to tell where the pointer has moved to
int count = 0;
ret = strstr(str, sub);
while (strstr(ret, sub) != NULL) {
printf("The substring is: %s\n", ret);
for (a = 0; a < strlen(sub); a++) {
ret++;
}
printf("The substring after moving pointer is: %s\n", ret);
count++;
}
return count - 1;
}
I don't understand what's happening here, I'm not using the null pointer once
strstr(ret,sub)
becomes null, so why is it giving me seg faults?
Valgrind would state that
Invalid read of size 1 and Address 0x0 is not stack'd, malloc'd or (recently) free'd
strstr()returnsNULL(inret), you are callingstrstr(NULL, ...)in the while loop. - dhke