Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Abort trap: 6" error in C?

Tags:

arrays

c

strcpy

I'm a beginner to C but I have this code running on xcode through gcc on terminal:

#include <stdio.h>
#include <string.h> 
int main(){
    char name[12] = "Roman Mirov"; 
    printf("My name is %s\n", name);
    name[8] = 'k'; 
    printf("My name is %s\n", name);
    char greeting[] = "hello"; 
    printf("%s %s\n", greeting, name);
    strcpy(greeting, "greetings, "); 
    printf("%s%s\n", greeting, name);
    return 0;
}

And it outputs this:

My name is Roman Mirov
My name is Roman Mikov
hello Roman Mikov
Abort trap: 6

My question exactly is, why it generates error instead of showing the last line as output "greetings, Roman Mikov"?

like image 394
Roman Avatar asked Dec 27 '16 07:12

Roman


1 Answers

In this case, the destination greeting does not have enough space to contain the whole contents of source, so it is an out of bounds access which invokes undefined behavior.

To elaborate, the size of array greeting is determined by the size of the supplied initializer,

char greeting[] = "hello";

in this case, "hello" which makes the size as 6, including the null-terminator.

Now, later you try to put a much bigger string into the memory,

strcpy(greeting, "greetings, ");

where, the source is of 12 bytes in size, whereas, the destination only contains 6. This causes the boundary overrun and the result, UB. The crash (or abort) is one of the possible side-effects of UB.

like image 189
Sourav Ghosh Avatar answered Sep 24 '22 17:09

Sourav Ghosh