当我取消引用 malloc 内的 NULL 指针时,为什么我的程序没有出现段错误? [英] Why doesn't my program seg fault when I dereference a NULL pointer inside of malloc?
问题描述
我一直使用这种 malloc 风格
I use this malloc style all the time
int *rc = 0;
rc = malloc(sizeof(*rc));
但是,即使当我调用 sizeof(*rc)
我假设 rc==0
并且我正在取消引用 时,它也不会出现段错误>NULL
指针.
However, it doesn't seg fault even though when I call sizeof(*rc)
I assume that rc==0
, and I am dereferencing a NULL
pointer.
推荐答案
你并没有真正取消引用任何东西.sizeof
的参数不会被计算,除非它是一个 VLA.语言明确允许将您想要的任何垃圾"作为 sizeof
的参数.该语言保证它不会评估任何内容,只需对表达式类型执行编译时分析.例如,表达式 sizeof i++
保证不会改变 i
的值.
You are not really dereferencing anything. The argument of sizeof
is not evaluated, unless it is a VLA. It is explicitly allowed by the language to put whatever "garbage" you want as the argument of sizeof
. The language guarantees that it will not evaluate anything, just perform compile-time analysis of the type of the expression. For example, expression sizeof i++
is guaranteed not to change the value of i
.
该规则的唯一例外是可变长度数组.VLA 的 sizeof
的结果是一个运行时值,这意味着该参数已被评估并且必须是有效的.
The only exception from that rule is Variable Length Arrays. The result of sizeof
for VLAs is a run-time value, which means that the argument is evaluated and must be valid.
这篇关于当我取消引用 malloc 内的 NULL 指针时,为什么我的程序没有出现段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!