“Abort trap: 6” error in C?

荒凉一梦 提交于 2019-12-04 13:05:33
Sourav Ghosh

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.

In this line, you are allocating an array of 5+1 characters:

char greeting[] = "hello";

In this line, you are attempting to write 11+1 characters into that array:

strcpy(greeting, "greetings, ");

In this case,greeting variable is array of char with size is 6 (Because hello and \0 ).

So when you use strcpy(greeting, "greetings, "); to copy "greetings, " into greeting is cannot. Because greeting not enough to contain array with 11+1 character

=> Has error abort trap : 6 here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!