I'm testing the perror function in C, and according to this page it prints a default message when a null pointer is passed:
int main(void)
{
int *p;
perror(p); //crashes
}
Cause int* p
contains a random/garbage value.
It is not an NULL
pointer. You need to explicitly initialize it with p = NULL;
.
Using an uninitialised variable is Undefined behaviour.
main()
also needs to return 0;
.
因为在C中p
不会自动初始化为0(这不是Java)。
int *p = 0;
Passing an invalid pointer to perror
is undefined behavior.
(C99, 7.1.4p1) "Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.