使用strtok时出现分段错误

问题描述 投票:0回答:2

在main中使用char *s时出现分割错误。如果我使用char s[100]或类似的东西就可以了。这是为什么?当我根据指令find_short(char *s)在线调用char *token = strtok(s, delim);函数时,将出现SIGSEGV。这是我的代码:

#include <sys/types.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>

int find_short(char *s)
{
    int min = INT_MAX;
    const char delim[2] = " ";
    char *token = strtok(s, delim);
    while(token != NULL) {
        int len = (int)strlen(token);
        if (min > len)
            min = len;
        token = strtok(NULL, delim);
    }
    return min;
}
int main()
{
    char *s = "lel qwew dasdqew";
    printf("%d",find_short(s));
    return 0;
}
c segmentation-fault substring min c-strings
2个回答
0
投票
我会在下面说这个。

对于当前程序,尽管C中的字符串文字没有常量字符数组类型,但它们是不可变的。任何更改字符串文字的尝试都会导致未定义的行为。然后,函数strtok更改传递给它的字符串,并在子字符串之间插入终止零。

代替函数strtok,应使用字符串函数strspnstrcspn。它们不会更改传递的参数。因此,使用这些功能,您还可以处理字符串文字。

这里是演示程序。

#include <stdio.h> #include <string.h> size_t find_short( const char *s ) { const char *delim= " \t"; size_t shortest = 0; while ( *s ) { s += strspn( s, delim ); const char *p = s; s += strcspn( s, delim ); size_t n = s - p; if ( shortest == 0 || ( n && n < shortest ) ) shortest = n; } return shortest; } int main(void) { const char *s = "lel qwew dasdqew"; printf( "%zu", find_short( s ) ); return 0; }

其输出为

3
© www.soinside.com 2019 - 2024. All rights reserved.