根据此,获取无效指针的值是C++中实现定义的行为.现在考虑以下C程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p=(int*)malloc(sizeof(int));
*p=3;
printf("%d\n",*p);
printf("%p\n",(void*)p);
free(p);
printf("%p\n",(void*)p); // Is this undefined or implementation defined in behaviour C?
}
Run Code Online (Sandbox Code Playgroud)
但是C中的行为也一样吗?上述C程序的行为是否未定义或实现定义?C99/C11标准对此有何看法?请告诉我C99和C11的行为是否不同.
在这个示例代码中,while循环后指针真的可以无效,并且在编写代码时是否应该考虑到这一点?或者C标准是否被误解和/或有缺陷?
#include <stdio.h>
int main(int argc, char **argv) {
(void)argc;
(void)argv;
int *pointer;
int object[1];
pointer = object;
printf("pointer -before: %p\n", (void*)pointer);
do {
int other_object[1];
printf("a pointer \"just past\" other_object can look like: %p\n", (void*)(&other_object+1));
printf("address of other_object: %p\n", (void*)&other_object);
} while (0);
puts("the lifetime of other_object has ended");
printf("pointer -after: %p\n", (void*)pointer);
}
Run Code Online (Sandbox Code Playgroud)
可能的输出(在我的机器上运行):
pointer -before: 0x7fff5f744ae4
a pointer "just past" other_object can look like: 0x7fff5f744ae4
address of other_object: 0x7fff5f744ae0
the lifetime of other_object has ended
pointer -after: …Run Code Online (Sandbox Code Playgroud)