scrblnrd3
scrblnrd3

Reputation: 7416

why am I getting a segfault when concatting strings?

I'm making a forest fire model which models a fire spread. Instead of showing the forest graphically, we were instructed to output the forest to the console as plain text. As a result, the output is very hard to distinguish, so I decided to color different elements, as such

int i;
int j;

//Initialize a string for what will be outputted to the screen
char output[2000]="";
//Initialize strings that will be concat'd to the main string
char tree[]= "\033[22;31m T \033[22;30m";
char burn[]=" B";
char dirt[]=" D";
char fizzled[]=" F";
char newl[]="\n";
for(i=0;i<25;i++){
    for(j=0;j<25;j++){
        if(forest[i][j]==1){
           strcat(output, tree);
        }else if(forest[i][j]==500){
            strcat(output,burn);
        }else if(forest[i][j]==-1){
            strcat(output,fizzled);
        }
        else{
            strcat(output,dirt);
        }

    }

    strcat(output,newl);

}
printf("------------------------------------------\n");
printf("%s",output);

The healthy trees are colored differently in the first iteration, as they should. However, it then returns a segfault, and I don't know why it happens.

Thanks

Upvotes: 0

Views: 106

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62058

It looks like you are overflowing your output array.

"\033[22;31m T \033[22;30m" is longer than some 15 characters (I didn't count precisely). In the worst case, when everything is trees you can get this pattern 25*25 times and the total will be greater than 15*25*25=9375 characters. And char output[2000] can only hold 2000 of them.

Btw, if you intend to use N characters in output[], you should reserve 1 more in the array for the NUL string terminator, '\0'.

Upvotes: 4

Related Questions