gpt4 book ai didi

c - 出于演示目的,如何打印悬挂指针?

转载 作者:太空狗 更新时间:2023-10-29 17:21:06 25 4
gpt4 key购买 nike

我正试图向某人解释为什么他们有悬空指针以及 free 实际是如何工作的(指针是值,因此是按值传递的),但为此我认为我需要一种打印指针的方法这不是“不确定的”(printf("%p", ptr) 就是这种情况)。

memcpy 会成功吗?

char buf1[sizeof(char *)];
char buf2[sizeof(char *)];
char *malloced = malloc(10);
memcpy(buf1, &malloced, sizeof(char *));
free(malloced);
memcpy(buf2, &malloced, sizeof(char *));
for (int i=0; i<sizeof(char *); i++) {
printf("%hhd %hhd / ", buf1[i], buf2[i]);
}

最佳答案

根据C标准的严格解读,你不能对悬垂指针做任何事情:“indeterminate”,存放悬垂指针的内存状态,也描述了未初始化的自动变量的内容,而这些may have different values if you read them twice in a row (*).

解决此问题的唯一方法是将指针转换为 uintptr_t 当它仍然有效时。转换的结果是一个整数,具有整数的性质:

#include <stdint.h>
...
char *malloced = malloc(10);
uintptr_t ptr_copy = (uintptr_t) malloced;
...
free(malloced);
// it is valid to use ptr_copy here to display what the address was.
printf("The pointer was at: %" PRIxPTR "\n", ptr_copy);

(*) C11 标准区分自动变量 the address of which is not taken (“that could have been declared with the register storage class”) ,但是 Clang does not care

要具体回答您关于使用 memcpy 的建议,请记下 that memcpy of indeterminate memory produces indeterminate memory

关于c - 出于演示目的,如何打印悬挂指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51344116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com