c - 核心转储在 char **指针上
问题描述
我知道分段错误发生在哪里,但不明白为什么。
我的主要功能是这样的:
int execute_line(char *line){
char **arguments;
int i = parse_args(arguments,line); //separates line in arguments
printf("Number of tokens: %d \n",i); //prints number of total tokens
printf("%s\n",arguments[0]); //print first token so I know it's not void
int r = check_internal(arguments); //segmentation fault
}
虽然 parse_args 函数填充如下参数:
int parse_args(char **args, char *line){
const char s[]= " \t\n\r";
char *token;
token = strtok(line, s);//separates line with the separators
int i=0;
char null[] = "(null)";
while( token != NULL ) {
if (token[0]=='#'){ //if the like begins with "comment" I don't care
args[i]=null;
return i;
}else{
args[i] = token;// else fills each char * of **args with a token
printf("Parse_args()--> token %d: ",i);
printf("%s\n",token);
i++;
}
token = strtok(NULL, s); //separates again
}
args[i]=null; //ends with null
return i;
}
我不明白为什么它会在 parse_args 正确返回标记后给出分段错误(因此至少填充了 **arguments)但是当我调用 int r = check_internal(arguments); 它给了我分段错误,(如果我在函数的第一行打印它不会显示,所以我想那是断点(打印调试 ftw))。
谁能指出我缺少指向正确内存部分的指针的位置?
错误:分段错误(核心转储)
check_internal: int check_internal(char **args);
如果我的输入是:
hey ho letsgo
程序返回:
Parse_args()--> token 0: hey
Parse_args()--> token 1: ho
Parse_args()--> token 2: letsgo
Number of tokens: 3
hey
Segmentation fault (core dumped)
感谢任何可以帮助我的人:D
解决方案
调用时parse_args
,arguments
未初始化。然后在内部parse_args
,当您分配给时,您取消引用这个未初始化的指针args[i]
。这样做会调用未定义的行为,这在这种情况下表现为崩溃。
声明arguments
为足以满足您的目的的指针数组:
char *arguments[100];
或者,如果您不知道您将拥有多少个参数,您可以改为传递 a 的地址char **
并在读取参数时为其动态分配内存:
int parse_args(char ***args, char *line){
const char s[]= " \t\n\r";
char *token;
token = strtok(line, s);//separates line with the separators
int i=0;
char null[] = "(null)";
*args = malloc(1 * sizeof(char *));
while( token != NULL ) {
if (token[0]=='#'){ //if the like begins with "comment" I don't care
(*args)[i]=null;
return i;
}else{
(*args)[i] = token;// else fills each char * of **args with a token
printf("Parse_args()--> token %d: ",i);
printf("%s\n",token);
i++;
}
*args = realloc(*args, i * sizeof(char *));
token = strtok(NULL, s); //separates again
}
(*args)[i]=null; //ends with null
return i;
}
并这样称呼它:
char **arguments;
int i = parse_args(&arguments,line);
推荐阅读
- python - 将数据框列表组合成一个新的数据框
- bash - 使用 sed 在文件中添加 sed 行
- javascript - 基于位置选择的着陆页重定向(Cookie?)
- c++ - 抽象类接口可以模板化吗
- r - 哪个正则表达式从文本中的引号中删除标点符号
- python - 如何将具有字符串和整数值的多个数据帧转换为 4D 数据结构
- reactjs - React 如何修复“滑动解锁”错误消息?
- javascript - 自定义元素原型中的覆盖函数会更改 this 对象
- reactjs - 禁用按钮的自定义样式也适用于常规按钮
- javascript - 如何对在画布上绘制的任意用户提交的 Javascript 代码进行沙箱处理?