- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正试图向某人解释为什么他们有悬空指针以及 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/
我试图使用 2 个文件描述符让父级向子级发送信息,并让子级将其发回。 #include #include #include #define READ 0 #define WRITE 1 int
我需要摆脱警告,其中之一是 -Wdangling-else。它在以下宏定义中记录了一个悬空 if: #define FOR_EACH_REF(var, container) \ if(bool
我使用eclipse进行php开发。我最近遇到了一个问题,IDE 会挂起,并且每当我打开 eclipse 时就会立即返回挂起状态。它说它卡在“初始化Java工具”上。我重新安装了多个版本的java和e
我想使用队列来保存结果,因为我希望消费者(串行而不是并行)在工作人员产生结果时处理工作人员的结果。 现在,我想知道为什么以下程序挂起。 import multiprocessing as mp imp
我是 ruby/rails 的新手,过去 2 天一直被一个问题搞得头晕目眩,希望这个论坛上的人能帮助我解决这个问题。 我正在使用 Rails 4 并使用 Passenger + Nginx 和 M
在堆上释放内存后 - vector 中仍保留(悬空)指针。如何完全删除 vector 元素? vector obstacles; vector actions; void Game::free(Ga
在编译器构造中,主要的歧义问题之一是dangling else。正如 Aho、Lam、Sethi 和 Ullman 在《编译器:原理、技术和工具》一书中提到的,悬空 else 的语法不能与 LL(1)
细节: ? Workspace name (e.g., org name) swag
我是一名优秀的程序员,十分优秀!