我如何打印悬空指针以进行演示? [英] How can I print a dangling pointer, for demonstration purposes?

查看:66
本文介绍了我如何打印悬空指针以进行演示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to explain to someone why they have a dangling pointer and how free actually works (and that pointers are values and thus are passed-by-value), but for that I think I need a way to print pointers that isn't "indeterminate" (as is the case with printf("%p", ptr)).

memcpy能做到吗?

Would memcpy do the trick?

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标准的严格阅读,您不能对悬空的指针执行任何操作:不确定",即保持悬空的内存状态指针,还描述了未初始化的自动变量的内容,如果您连续两次读取这些可能会有不同的值(*).

According to a strict reading of the C standards, you can't do anything with a dangling pointer: "indeterminate", the state of memory that holds a dangling pointer, also describes the contents of uninitialized automatic variables, and these may have different values if you read them twice in a row(*).

解决此问题的唯一方法是将指针转换为 uintptr_t 仍然有效的.转换的结果是一个整数,并具有整数的属性:

The only way around the issue is to convert the pointer to uintptr_t while it is still valid. The result of the conversion is an integer and has the properties of integers:

#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标准区分自动变量地址 ,但是 Clang不接受护理.

(*) The C11 standard distinguishes automatic variables the address of which is not taken ("that could have been declared with the register storage class"), but Clang does not care.

要具体回答您使用 memcpy 的建议,请注意那是 memcpy 产生不确定内存.

To answer specifically your suggestion of using memcpy, note that memcpy of indeterminate memory produces indeterminate memory.

这篇关于我如何打印悬空指针以进行演示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆