我正在用C编写一个汇编程序,该程序采用(组合结构的)汇编代码并对其进行操作以创建可执行程序。
我要解析的行是:
jmp L1
这是我正在使用的代码:
int line_count = 0;
char line[MAX_LINE_LENGTH];
char original_line[MAX_LINE_LENGTH];
char *first_field;
char label[MAX_LABEL_LENGTH];
char *argument;
int arguments_in_line = 0;
while(fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
line_count++;
strcpy(original_line, line);
first_field = strtok(line, delimit);
if(is_valid_label(first_field)) { /* first field is label */
strcpy(label,first_field);
first_field = strtok(NULL, delimit);
}
if(!is_entry_or_external(first_field)) {
arguments_in_line = get_num_operands(original_line);
if(arguments_in_line == UNEXPECTED_ERROR)
return UNEXPECTED_ERROR;
else if(arguments_in_line == 0) {
continue;
}
else if(arguments_in_line == 1) {
argument = strtok(NULL, delimit);
if(is_valid_label_name(argument)) /* SEGFAULT HERE!!! */
printf("found needed replacement at line %d, replace label: %s", line_count, argument);
}
}
}
因此在strtok的第二个或第三个(取决于输入,对于示例行而言,它是第二个)调用,参数获取NULL并出现段错误。 调用strtok之前的值为:
(gdb) p line
$1 = "jmp L1\000\000\000\000\000\000[q\346\267\000\360... /* more values */
第一次通话后:
(gdb) p line
$2 = "jmp\000L1\000\000\000\000\000\000[q\346\267\000\360... /* more values */
第二个返回NULL。
方法get_num_operands
如下:
int get_num_operands(char *src_line) {
char line_copy[MAX_LINE_LENGTH];
char *first_field;
strcpy(line_copy, src_line);
first_field = strtok(line_copy, delimit);
if(is_valid_label(first_field)) /* first field is label */
first_field = strtok(NULL, delimit); /* make sure first field is a command or instruciton */
if (first_field == NULL)
return UNEXPECTED_ERROR;
else
return get_num_arguments_for_command(first_field);
}
关于为什么发生这种情况的任何想法吗?