进入的char * str中没有malloc的,无段错误? [英] gets into char *str without malloc, no segfault?

查看:193
本文介绍了进入的char * str中没有malloc的,无段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚编译使用Cygwin的GCC这个C程序:

I've just compiled this C program using Cygwin's gcc:

#include <stdio.h>

void main (){
    char *str;
    gets(str);
    printf("%s",str);
}

撇开获得德precated 走了,这是应该打破,因为我不是为海峡分配任何内存,但它的工作原理,甚至很长的输入。如果,例如,我设置字符海峡[16]它只需几个字符超过分配的长度后,打破了。

Setting aside gets is deprecated gone, this is supposed to break since I'm not allocating any memory for str, but it works even with very long inputs. If, for example, I set char str[16] it breaks after exceeding the allocated length by just a few characters.

为什么我没有收到分段错误?

How come I'm not getting a segmentation fault?

推荐答案

访问内存区域指向未初始化的指针的未定义行为后,它可能会崩溃,但也可能看起来像正常工作。总之,你不能predict其行为。

Access memory region pointed to by uninitialized pointer is undefined behavior, it could crash, it also could look like working normally. In a word, you cannot predict its behavior.

为什么我没有收到分段错误?

How come I'm not getting a segmentation fault?

未初始化的指针有一个不确定的值,它可能指向任何地方,如果它指出了一些足够大的可写域意外,该方案将工作正常。

Uninitialized pointer has an undetermined value, it could point to anywhere, if it points to some big enough writable region accidently, that program will "work" normally.

这篇关于进入的char * str中没有malloc的,无段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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