gets into char *str without malloc, no segfault?

♀尐吖头ヾ 提交于 2019-12-02 18:19:10

问题


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

#include <stdio.h>

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

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?


回答1:


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.




回答2:


The variable str has an undefined value. It means that it simply gets a place on the stack and the value which was there happens to be inside this variable. A possible explication of your behaviour is that a builtin function initializing process environment and invoking your main used this place for a meaningful pointer to some accessible memory. The value of this pointer stayed on the stack and when your main was invoked it happened that str got this value. But this is just one of possible explications.



来源:https://stackoverflow.com/questions/22653370/gets-into-char-str-without-malloc-no-segfault

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