Redian新闻
>
今天是个好日子,献湿一手
avatar
今天是个好日子,献湿一手# Joke - 肚皮舞运动
h*m
1
我写了个简单的程序:
int a[3];
for(i=0; i<5; i++)
{
a[i] = i;
printf("%d, ", a[i]);
}
为啥能输出0,1,2,3,4而不报错呢?
我试了一下用 int *a = malloc(3*sizeof(int))
同样的也不报错。
avatar
M*S
2
十年光棍非本意,
从戎报国打飞机。
忽忆军中一空姐,
帐中老兵如塔立。
MTAS作于空姐生日光棍节老兵节空军建军节,二零一零年十一月十一日
avatar
M7
3
what is your compiler?
compiled with gcc, your program gets seg fault.
I think the original C leaves the boundary check responsibility to the
programmer.

【在 h********m 的大作中提到】
: 我写了个简单的程序:
: int a[3];
: for(i=0; i<5; i++)
: {
: a[i] = i;
: printf("%d, ", a[i]);
: }
: 为啥能输出0,1,2,3,4而不报错呢?
: 我试了一下用 int *a = malloc(3*sizeof(int))
: 同样的也不报错。

avatar
C*g
4
莎士比亚?

十年光棍非本意,
从戎报国打飞机。
忽忆军中一空姐,
帐中老兵如塔立。
MTAS作于空姐生日光棍节老兵节空军建军节,二零一零年十一月十一日

【在 M**S 的大作中提到】
: 十年光棍非本意,
: 从戎报国打飞机。
: 忽忆军中一空姐,
: 帐中老兵如塔立。
: MTAS作于空姐生日光棍节老兵节空军建军节,二零一零年十一月十一日

avatar
S*I
5
this is called "undefined behavior" in C/C++, which means anything could
happen, including the one looks like working correctly.

【在 h********m 的大作中提到】
: 我写了个简单的程序:
: int a[3];
: for(i=0; i<5; i++)
: {
: a[i] = i;
: printf("%d, ", a[i]);
: }
: 为啥能输出0,1,2,3,4而不报错呢?
: 我试了一下用 int *a = malloc(3*sizeof(int))
: 同样的也不报错。

avatar
h*m
6
我用的就是ubuntun下面自带的gcc阿

【在 M7 的大作中提到】
: what is your compiler?
: compiled with gcc, your program gets seg fault.
: I think the original C leaves the boundary check responsibility to the
: programmer.

avatar
M7
7
hehe, I think we have a perfect example of "undefined behavior".

【在 h********m 的大作中提到】
: 我用的就是ubuntun下面自带的gcc阿
avatar
l*a
8
you write the data into address:a+3/a+4,
since no one else use them ,nothing happened
but once you allocate memory from a+3 and already used them for another
variable/object,
you will never know who changed the content
this is different from access violation and segment fault

【在 h********m 的大作中提到】
: 我写了个简单的程序:
: int a[3];
: for(i=0; i<5; i++)
: {
: a[i] = i;
: printf("%d, ", a[i]);
: }
: 为啥能输出0,1,2,3,4而不报错呢?
: 我试了一下用 int *a = malloc(3*sizeof(int))
: 同样的也不报错。

avatar
h*m
9
谢谢大家的回复!我还以为这种情况compiler总要报错呢。看来用C真是要小心啊。
avatar
h*m
10
在网上查了一下,好像有的地方给的segment fault的example就是array assign的值大
于array定义阿?

【在 l*****a 的大作中提到】
: you write the data into address:a+3/a+4,
: since no one else use them ,nothing happened
: but once you allocate memory from a+3 and already used them for another
: variable/object,
: you will never know who changed the content
: this is different from access violation and segment fault

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。