这是完整的代码
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;
}
我不明白这里发生了什么,我没有使用空指针
strstr(ret,sub)
变为null,为什么它会给我seg错误?
Valgrind会说明
读取大小1和 地址0x0不stack'd,malloc分配或(最近)free'd
答案 0 :(得分:6)
您不会测试初始通话ret = strstr(str,sub);
是否成功。
如果它返回NULL
,则下一个调用strstr(ret,sub)
肯定会调用未定义的行为。
此外,您的代码未在ret
循环中正确更新while
,您必须将ret
设置为匹配后的第一个字符,而不仅仅是按照比赛。这是一个更简单的版本:
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;
}
答案 1 :(得分:0)
你一定要检查strstr(man strstr(3))的返回值:
RETURN VALUE These functions return a pointer to the beginning of the located substring, or NULL if the substring is not found.