"Abort trap: 6" running C program on a Mac

1.8k views Asked by At

I have a problem with this program. When I try to run it on my Mac, it returns "Abort trap: 6". I cannot understand the reason.

Below is the file contents I used to test the program.

aaabccdegags
bbbbbbbcados
vbaiusbyabtd
aisybavsitvc
asindvsivati
ammaccabanan

You should just copy these nonsense strings into a text file file.txt and call it by the command prompt with the syntax:

program.exe file.txt r

where file.txt includes the nonsense strings and r is the letter it should look for in the text file.

#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

There are 1 answers

0
Sourav Ghosh On

I did not run your code with the given inputs, but without that, it looks like, you're facing UB in your code. In the case of the statement

 strcpy(posizione,"orizzontale");

the source string is of more length than the destination can hold. It tries to write past the allocated memory which in turn invokes undefined behaviour.