问题描述
我一直使用这种 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 指针时,为什么我的程序没有段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!