gets into char *str without malloc, no segfault?

后端 未结 2 1135
我在风中等你
我在风中等你 2021-01-28 22:41

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

#include 

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


        
相关标签:
2条回答
  • 2021-01-28 23:23

    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.

    0 讨论(0)
  • 2021-01-28 23:31

    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.

    0 讨论(0)
提交回复
热议问题