malloc(0)C11标准中的行为引用以下*:
void*malloc(size_t size);
如果size为零,则行为是实现定义的(可能返回空指针,或者可能返回一些非空指针,这些指针可能不用于访问存储,但必须传递给free).
*(引自cppreference.com而不是官方的ISO/IEC 9899:2011标准,因为前者需要购买.)
有了这个定义,我就不会期望以下工作(用icc18.0.0 编译):
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
double *u = malloc(0);
u[0] = 3.0;
printf("The value of u[0] is %lf", u[0]);
free(u);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是它起作用并给出了输出:
The value of u[0] is 3.000000
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
它似乎u[0] = 3.0;访问存储.如果malloc返回NULL,则会导致分段错误.
我是否误解了访问存储的概念,或者是否还有其他事情发生?
更新/澄清
似乎我的问题的关键在于" 可能不会用于访问存储 " 的措辞,以及"可能不"意味着不应该或 …
int my_func(void) {
if(/*condition*/) {
return 1;
}
else if (/*other condition*/) {
return 2;
}
return 3;
}
int x = my_func();
Run Code Online (Sandbox Code Playgroud)
是否x保证始终是 3 个可能值之一?
以标准或 POSIX 或其他合法来源的引用形式提供证明。如果没有这样的来源,请提供逻辑证明(gcc/汇编)。