这是我的主语:
int main() {
char *x = "add r3,r5";
char *t;
char **end;
t = getFirstTok(x,end);
printf("%s",t);
}以及函数getFirstTok:
/* 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中断)
谢谢。
发布于 2021-02-19 15:48:10
正如注释中所指出的,字符串文字是只读的,因为它们是在编译的程序中烘焙出来的。如果您不想使用建议的解决方案,即将“源程序”变成堆栈分配的字符数组(char x[] = "add r3,r5"),可以使用像strdup(3)这样的函数来生成如下所示的可读/可写副本:
#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 = "...",因为编译器通常会在以后尝试向它们写入时警告我。
https://stackoverflow.com/questions/66280345
复制相似问题