2015-06-17 38 views
0

我有这个程序的问题。当我尝试在我的Mac上运行它时,它会返回“中止陷阱:6”。我无法理解原因。“中止陷阱:6”在Mac上运行C程序

以下是我用来测试程序的文件内容。

aaabccdegags
bbbbbbbcados
vbaiusbyabtd
aisybavsitvc
asindvsivati
ammaccabanan

您应该将这些废话字符串只是复制到一个文本文件file.txt,并通过与语法在命令提示符下调用它:

program.exe file.txt r

其中file.txt包含无意义的字符串,r是它应该在文本文件中查找的字母。

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 
#define R 24 
#define C 71 

int main(int argc, char * argv[]) { 

if (argc!=3){ 
    printf("Errore acquisizione parametri\n"); 
    return -1; 
} 

FILE*fp; 
char m[R][C],c,posizione[10]; 
int i,j,lstr,numrighe,quante,quantemax,posiz,x,y,maxmax; 

maxmax=0; 

//posiz=1 se orizzontale 

quantemax=0; 

sscanf(argv[2],"%c",&c); 

fp=fopen(argv[1],"r"); 

if (fp==NULL){ 
    printf("Errore apertura file\n"); 
    return -3; 
} 

for (i=0;i<R && (!feof(fp));i++){ 
    fgets(m[i],C,fp); 
} 

fclose(fp); 

lstr=strlen(m[0]); 

numrighe=i; 

for (i=0;i<lstr;i++){ 

    quante=0; 

    for (j=0;j<numrighe;j++) { 
     if (m[i][j]==m[i][j+1]){ 
      quante++; 
      if (quante>quantemax){ 
       quantemax=quante; 
       if (quantemax>maxmax){ 
       y=i; 
       x=j; 
       posiz=1; 
       } 
      } 
     } 
    } 
} 

for (i=0;i<lstr;i++){ 

    quante=0; 

    for (j=0;j<numrighe;j++) { 
     if (m[i][j]==m[i+1][j]){ 
      quante++; 
      if (quante>quantemax){ 
       quantemax=quante; 
       if (quantemax>maxmax){ 
       y=i; 
       x=j; 
       posiz=0; 
       } 
      } 
     } 
    } 
} 

if (posiz==1){ 
    strcpy(posizione,"orizzontale"); 
} 

else { 
    if (posiz==0){ 
     strcpy(posizione,"verticale"); 
    } 
} 


printf("La stringa con il maggior numero di %c consecutive, si trova in %s a partire dalla posizione %d,%d",c,posizione,x,y); 

return 0; 
} 
+1

建议:'!feof(fp)'往往是错误的。 –

+1

您是否可以使用调试器来查明确切的错误指令? –

回答

2

我没有用给定的输入运行你的代码,但没有,它看起来像,你在代码中面临着UB。在声明的情况下

strcpy(posizione,"orizzontale"); 

源字符串的长度比目标可以容纳的长度长。它试图写入分配的内存,然后调用undefined behaviour