“中止陷阱:6"表示“中止陷阱:6". C错误? [英] "Abort trap: 6" error in C?

查看:78
本文介绍了“中止陷阱:6"表示“中止陷阱:6". C错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的初学者,但是我通过终端上的gcc在xcode上运行了这段代码:

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;
}

它输出以下内容:

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

我的问题恰恰是,为什么它生成错误而不是将最后一行显示为输出"greetings,Roman Mikov"?

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

推荐答案

在这种情况下,目标greeting没有足够的空间来容纳 source 的全部内容,因此它是一个超出范围的访问会调用未定义的行为.

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.

详细地说,数组greeting的大小由提供的初始化程序的大小

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

char greeting[] = "hello";

在这种情况下,"hello"的大小为6,包括空终止符.

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

现在,稍后您尝试将更大的 string 放入内存中,

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

strcpy(greeting, "greetings, ");

其中,源的大小为12个字节,而目标的大小仅为6个字节.这会导致边界超限和结果UB.崩溃(或中止)是UB的可能副作用之一.

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.

这篇关于“中止陷阱:6"表示“中止陷阱:6". C错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆