【发布时间】:2017-07-06 06:25:51
【问题描述】:
所以,我正在为 LC3b 机器编写解释器。我需要编写一个函数来检查输入是否是有效的操作码。为此,我编写了如下函数:
int isOpcode(char* oput)//oput=Opcode under test
{
FILE* isa_file = NULL;
int i,j;
char * line = NULL;
size_t len = 0;
ssize_t nread;
//printf("Entered opcode checking function \n");
/*convert to lower case */
//for( i = 0; i < strlen( oput ); i++ )
// oput[i] = tolower( oput[i] );
//printf("Entered opcode checking function1 \n");
/*for modularity, using the file */
isa_file = fopen("isa", "r");
if(isa_file == NULL)
printf("Error in file opening\n");
int flag;
while ((nread = getline(&line, &len, isa_file)) != -1)
{
printf("Retrieved line of length %zu :\n", nread);
printf("%s", line);
//Solving the new line character problem which resulted in the improper difference of strcmp ..now it is proper...
//char final[strlen(line)-1];
//strcpy(final,line);
//final[strlen(line)-1]='\0';
// printf("Entered opcode checking function2 \n");
// printf("%s \n",oput);
// overwrite \n with nul-terminator
line[strcspn(line, "\n")] = 0;
char final[strlen(line)];
strcpy(final,line);
flag=strcmp(oput,final);
printf("%s \n",oput);
printf("flag: %d \n",flag );
if(flag < 0 || flag >0)
{
flag=-1;
//printf("entered 1st condition \n");
printf("final flag: %d \n", flag);
}
else
{
flag=1;
//printf("entered negative \n");
printf("final flag: %d \n", flag);
break;
}
}
printf("end of loop \n");//this is not getting printed
fclose(isa_file);
if (line)
free(line);
return flag;
}
现在,当我使用其中一个有效操作码调用函数时,函数会打印最终标志 (=1),然后进入分段错误。它甚至不打印循环语句的结尾。有人可以告诉我有什么问题吗?我尝试将这个函数的一部分作为单独的文件执行,它似乎工作得很好。
更新: 当我注释掉 toLower 代码时,循环语句的结尾现在会打印在屏幕上。但是,即使这样,代码也会引发段错误。有趣的是,仅当最终标志设置为 1 时才会引发错误。否则,它可以正常工作!我无法理解这个奇怪的问题!
【问题讨论】:
-
final[strlen(line)-1]='\0';不是减一吗? -
并在调用
fopen后检查isa_file是否为NULL。 -
return flag;应该是free和file close之后,明显是检查文件是否正确打开和行分配 -
char final[strlen(line)-1];关闭 2 ==>char final[strlen(line)+1]; -
不要使用名为
read的对象,有一个同名的函数。我们通常将其命名为nread以表示读取的字节数。
标签: c segmentation-fault