通过嵌套结构访问指针
struct x {
int *u;
};
struct y {
struct x *z;
};
int main()
{
static y b;
static int g=7;
b.z->u=&g;
}
语句bz->u=&g
给出了分段错误。如果我删除 int g
前面的 static
:
int g=7;
b.z->u=&g;
代码将正确执行。
struct x {
int *u;
};
struct y {
struct x *z;
};
int main()
{
static y b;
static int g=7;
b.z->u=&g;
}
The statement b.z->u=&g
gives a segmentation error. If I remove the static
in front of int g
:
int g=7;
b.z->u=&g;
The code executes properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
bz
尚未初始化。您可以使用以下方式初始化b
:但其成员字段
z
仍然是一个空指针(指向某个随机位置)。因此,当您访问某些随机内存时,访问其成员u
会导致分段错误。我想这样应该可行(没有尝试):
为什么你的第二个例子有效,我不知道。我怀疑这是因为“运气”......
b.z
is not yet initialized. You initializeb
with:but its member field
z
is still a null pointer (pointing so some random location). So accessing its memberu
results in an segmentation error as you are accessing some random memory.I suppose that like this should work (did not try):
Why your second example works, I do not know. I suspect it is due to 'luck'...
因为
bz
尚未设置为指向任何有用的位置。它目前只是一个NULL
指针。*您需要执行以下操作:
首先(即创建一个实际对象)。
请记住在某个时候
释放
它。* 请注意,它只是
NULL
,因为b
被声明为static
。如果b
是非静态
,它将指向内存中随机的某个位置。Because
b.z
hasn't been set to point anywhere useful. It's currently just aNULL
pointer.*You need to do something along the lines of:
first (i.e. create an actual object).
Remember to
free
this at some point.* Note that it's only
NULL
becauseb
is declared asstatic
. Ifb
were non-static
, it would be pointing at somewhere random in memory.它会给你一个分段错误,因为你正在做的是未定义的行为。您正在访问结构体的
z
指针,但没有对其进行初始化(即,没有为其提供指向的内存空间)。事实上,在变量不是静态的情况下,它不会给您带来分段错误,这一事实并不重要,因为对未初始化指针的整个访问都是错误的。It will give you a segmentation error, because what you're doing is undefined behavior. You're accessing the
z
pointer of the structure without initializing it (that is, without giving it a memory space to point to). The fact that it is not giving you a segmentation error in the case the variable is not static is not important, as the whole access to an uninitialized pointer is wrong.您从未为
bz
分配内存。您的bz
包含未初始化的垃圾值,这就是为什么尝试取消引用bz
(在bz->u
中)会导致分段错误。PS 您声明了您的对象
static
,这意味着bz
最初包含一个空值(而不是我上面所说的“未初始化的垃圾值”)。然而,取消引用空指针也是未定义的。You never allocated memory for your
b.z
. Yourb.z
contains an uninitialized garbage value, which is why trying to dereferenceb.z
(inb.z->u
) causes a segmentation fault.P.S. You declared your objects
static
, which means thatb.z
initially contains a null value (not an "uninitialized garbage value" as I stated above). Nevertheless, dereferencing a null pointer is also undefined.