C语言 通过union共存体释放常量指针指向的堆空间

union共存体中所有成员占用相同的内存空间。
因为free函数参数是void *,常量指针是const void *,所以free函数释放常量指针时会因类型不同而失败。

#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef union _const_ptr
{
const void *cp;
void *vp;
} const_ptr;
void free_const_ptr(const void *cp)
{
if (!cp)
{
return;
}
const_ptr ptr = {.cp = cp};
free(ptr.vp);
}
int main()
{
char a[20] = "123";
const char *b = strdup(a);
printf("%s\n", b);
// free(b);
free_const_ptr(b);
return 0;
}

 

posted on   王景迁  阅读(37)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示