c - 自由指针偏移不再有效?
问题描述
我本可以发誓这段代码应该可以工作,但现在看来它出现了段错误。任何人都知道这是一直如此还是glibc的变化?
....
char *tmp = malloc(50);
tmp = &tmp[10];
free(tmp); // segfault
// I thought as long as the pointer was within a valid memory block,
// the free was valid. Obviously I know not to double free, but this
// means any pointer offsets must be kept along with the original malloced
// pointer for the free operation.
解决方案
此代码段
char *tmp = malloc(50);
tmp = &tmp[10];
free(tmp); // segfault
// I thought as long as the
无效,因为在此语句之后
tmp = &tmp[10];
指针 tmp 没有动态分配的内存范围的地址。所以下一个语句
free(tmp);
调用未定义的行为。
来自 C 标准(7.22.3.3 自由函数)
否则,如果参数与内存管理函数先前返回的指针不匹配,或者如果空间已通过调用 free 或 realloc 被释放,则行为未定义。
你可以写
tmp = &tmp[10];
//...
free(tmp - 10 );
或者您似乎需要重新分配早期分配的内存,例如
char *tmp = malloc(50);
char *tmp2 = realloc( tmp, 10 );
if ( tmp2 != NULL ) tmp = tmp2;
推荐阅读
- javascript - 有没有办法在谷歌地图回调中包含对象原型方法?
- google-app-engine - 在 AppEngine(Python) 中连接到 Google Cloud MySQL 数据库
- java - 如何将字符串拆分为整数、符号和字符串,然后存储整数值以用于算术运算
- php - 如何在没有 for 循环的情况下在 Twig 中按键访问值
- c# - 将 Xml Api 字符串转换为 Json 字符串 UWP
- javascript - php处理完成后如何在SQLite表中插入数据?
- gnuplot - 如何使用 gnuplot 从计算数据中绘制磁场线?
- node.js - 如何修复 npm ERR!peer dep 缺失:discord.js@11.5.1 需要的 node-opus@^0.2.7?
- reactjs - Google Calendar API 是否允许在多供应商 React Web 应用程序中安排约会?
- performance - 在 GPU 上运行多个深度学习模型时如何优化