[英]Segmentation fault in c (C90), Whats the problem?
这是我的 main.c:
int main() {
char *x = "add r3,r5";
char *t;
char **end;
t = getFirstTok(x,end);
printf("%s",t);
}
function 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;
}
为什么我在运行这个主程序时会出现分段错误? 我正在编写一个两遍汇编程序,我需要一个 function 来通过分隔符解析字符串,在这种情况下是空格。 为此目的使用 strtok 会更好吗?
我需要一个命令解析器 - 这样它就可以提取“add”,一个操作数解析器(按分隔符),提取“r3”和“r5”。 我想检查这个 getFirstTok function 是否适合这个目的,但是当我尝试运行它时,我遇到了分段错误:
进程以退出代码 139 结束(被信号 11 中断:SIGSEGV)
谢谢你。
正如评论中所指出的,字符串文字是只读的,因为它们被烘焙到编译的程序中。 如果您不想 go 使用建议的解决方案,使您的“源程序”成为堆栈分配的字符数组( char x[] = "add r3,r5"
),您可以使用 function 像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 = "..."
,因为如果我稍后尝试写入它们,编译器通常会警告我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.