为什么这个strstr实例会给我分段错误?

use*_*193 2 c

这是完整的代码

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;  
}
Run Code Online (Sandbox Code Playgroud)

我不明白这里发生了什么,我没有使用空指针一次

strstr(ret,sub) 
Run Code Online (Sandbox Code Playgroud)

变为null,为什么它会给我seg错误?

Valgrind会说明这一点

无效读取大小1和地址0x0未堆叠,malloc'd或(最近)free'd

chq*_*lie 6

您不测试初始呼叫是否ret = strstr(str,sub);成功.

如果它返回NULL,则下一个调用strstr(ret,sub)肯定会调用未定义的行为.

此外,您的代码retwhile循环中没有正确更新,您必须设置ret为匹配后的第一个char,而不仅仅是按匹配的长度推进它.这是一个更简单的版本:

int count_substr(const char *str, const char *sub) {
    /* returns the number of non overlapping matches of sub in str */
    const char *ret = str;   
    int count = 0;

    if (ret && sub && *sub != '\0') {
        while ((ret = strstr(ret, sub)) != NULL) {
            ret += strlen(sub);
            count++;
        }
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)