以下 C 代码编译并运行,但它是未定义的行为吗?

P. *_*ich 4 c pointers undefined-behavior

我发布了一个关于我之前在这个问题中遇到的一些指针问题的问题: C int 指针分段错误几种情况,无法解释行为

从一些评论中,我被引导相信以下几点:

#include <stdlib.h>
#include <stdio.h>
int main(){
   int *p;
   *p = 1;
   printf("%d\n", *p);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

是未定义的行为。这是真的?我一直这样做,我什至在我的 C 课程中看到过。但是,当我这样做时

#include <stdlib.h>
#include <stdio.h>
int main(){
   int *p=NULL;
   *p = 1;
   printf("%d\n", *p);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

在打印p(行之后*p=1;)的内容之前,我遇到了段错误。这是否意味着我应该在malloc任何时候为要指向的指针分配值时一直在ing?

如果是这样,那为什么char *string = "this is a string"总是有效?

我很困惑,请帮忙!

dbu*_*ush 7

这个:

int *p;
*p = 1;
Run Code Online (Sandbox Code Playgroud)

是未定义的行为,因为p没有指向任何地方。它是未初始化的。因此,当您尝试取消引用时,p您实际上是在写入一个随机地址。

什么不确定的行为方式是不能保证什么程序就行了。它可能会崩溃,可能会输出奇怪的结果,或者它可能看起来工作正常。

这也是未定义的行为:

int *p=NULL;
*p = 1;
Run Code Online (Sandbox Code Playgroud)

因为您试图取消引用 NULL 指针。

这有效:

char *string = "this is a string" ;
Run Code Online (Sandbox Code Playgroud)

因为您正在string使用字符串常量的地址进行初始化。这与其他两种情况不同。它实际上与此相同:

char *string;
string = "this is a string";
Run Code Online (Sandbox Code Playgroud)

请注意,此处string并未取消引用。指针变量本身被赋值。