首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C (C90)中的分割故障,问题是什么?

C (C90)中的分割故障,问题是什么?
EN

Stack Overflow用户
提问于 2021-02-19 15:25:16
回答 1查看 69关注 0票数 1

这是我的主语:

代码语言:javascript
复制
int main() {
    char *x = "add r3,r5";


    char *t;
    char **end;

    t = getFirstTok(x,end);
    printf("%s",t);
}

以及函数getFirstTok:

代码语言:javascript
复制
/* getFirstTok function returns a pointer to the start of the first token. */
/* Also makes *endOfTok (if it's not NULL) to point at the last char after the token. */
char *getFirstTok(char *str, char **endOfTok)
{
    char *tokStart = str;
    char *tokEnd = NULL;

    /* Trim the start */
    trimLeftStr(&tokStart);

    /* Find the end of the first word */
    tokEnd = tokStart;
    while (*tokEnd != '\0' && !isspace(*tokEnd))
    {
        tokEnd++;
    }

    /* Add \0 at the end if needed */
    if (*tokEnd != '\0')
    {
        *tokEnd = '\0';
        tokEnd++;
    }

    /* Make *endOfTok (if it's not NULL) to point at the last char after the token */
    if (endOfTok)
    {
        *endOfTok = tokEnd;
    }
    return tokStart;
}

为什么我在运行这个主程序时会有分割错误?我正在编写一个二次传递的抗震器,我需要一个函数,它通过分隔符解析一个字符串,在本例中是一个空格。用strtok代替这个用途更好吗?

我需要一个命令过路器--这样它就可以提取"add",一个操作数解析器(By,定界符),以提取"r3“和"r5”。我想检查这个getFirstTok函数是否适合这个目的,但是当我尝试运行它时,我会得到一个分段错误:

处理完成了出口代码139 (被信号11: SIGSEGV中断)

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-02-19 15:48:10

正如注释中所指出的,字符串文字是只读的,因为它们是在编译的程序中烘焙出来的。如果您不想使用建议的解决方案,即将“源程序”变成堆栈分配的字符数组(char x[] = "add r3,r5"),可以使用像strdup(3)这样的函数来生成如下所示的可读/可写副本:

代码语言:javascript
复制
#include <string.h>

[...]

char *rw_code = strdup(x);
t = getFirstTok(rw_code, end);
printf("%s", t);
free(rw_code); /* NOTE: invalidates _all_ references pointing at it! */

[...]

另外,我总是使字符串常量为const char *lit = "...",因为编译器通常会在以后尝试向它们写入时警告我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66280345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档