小编use*_*193的帖子

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

这是完整的代码

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

c

2
推荐指数
1
解决办法
1018
查看次数

标签 统计

c ×1