【问题标题】:"Abort trap: 6" running C program on a Mac“中止陷阱:6”在 Mac 上运行 C 程序
【发布时间】:2015-09-02 14:30:03
【问题描述】:

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

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

aaabccdegags
bbbbbbbcados
vbaiusbyabtd
aisybavsitvc
asindvsivati
ammaccabanan

您应该将这些无意义的字符串复制到文本文件file.txt 中,然后通过命令提示符使用以下语法调用它:

program.exe 文件.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;
}

【问题讨论】:

  • 建议:!feof(fp) 往往是错误的。
  • 你可以使用调试器来查明确切的错误指令吗?

标签: c macos abort


【解决方案1】:

我没有使用给定的输入运行您的代码,但如果没有它,您的代码中似乎面临着 UB。在声明的情况下

 strcpy(posizione,"orizzontale");

源字符串的长度超过了目标字符串的长度。它尝试写入分配的内存,然后调用undefined behaviour

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2017-05-11
    相关资源
    最近更新 更多