【问题标题】:How to get rid of this segmentation error?如何摆脱这种分割错误?
【发布时间】:2017-04-04 03:48:32
【问题描述】:
void search(FILE *fp){
  char lines[81];
  char iden[11];


int i = 0;
  int count = 1;
     while(!feof(fp)){
       fgets(lines,80,fp);
       // If the line dosesn't start with #, space, or tab, it has identifier
       if (lines[0] != '#' && lines[0] != ' ' && lines[0] != '\t'){
       // An identifier ends with ':'
         while (lines[i] != ':'){
           iden[i] = lines[i];
           ++i;
         }
         ins(iden, count);
       }
            ++count;
  }
}

我收到这样的错误:

p4.c:93:12:运行时错误:索引 11 超出类型“char [11]”的范围

p4.c:92:17:运行时错误:索引 81 超出类型“char [81]”的范围

p4.c:93:22:运行时错误:索引 81 超出类型“char [81]”的范围

分段错误

注意:我的输入文件包含根据上述错误检查的数据。我的意思是每行最多 80 个字符,包括 \n,标识符的最大大小为 10。不以“#”或空格或制表符开头的行在以 ' 结尾的行开头包含一个标识符:' 最大大小为 10,包括 ':'

在上述代码的第二个 while 循环中发生了吗? 为什么会出现此错误?

p.s:我已经打开了我的文件并在我的 main 方法中检查了它

【问题讨论】:

标签: c file segmentation-fault runtime-error


【解决方案1】:

您永远不会重置计数器 i,也不会在标识符中添加终止符。

那就试试吧:

i=0;
while (lines[i] != ':'){
     iden[i] = lines[i];
     ++i;
 }
 iden[i]='\0';

但为了安全起见,您应该采取保护措施,以便实际使用:

while (lines[i] != ':' && i<10){

永远不要相信输入,并始终确保您的程序永远不会超出其变量的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-15
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多