c-释放后使用ASAN堆



我运行ASAN是为了在一个非常大的项目中查找内存泄漏。我已经找到了原因,但不知道如何解决。我制作了一个示例程序来让问题变得可以理解。在下面的程序中,我只能处理指定的代码。对于代码的其余部分,不可能进行变通。因此,请建议我可能需要解决以下ASAN错误的工作。(如何使用t1使指针2为NULL?(

#include<stdio.h>
#include<stdlib.h>
typedef struct l
{
int a, b;
}pack;
void delete_me(pack *ap)
{
free(ap);
}
int main(void)
{
pack **d_ptr = (pack **)malloc(3 * sizeof(pack *));
pack *one, *two, *three;
one = (pack *)malloc(sizeof(pack));
one->a = 1, one->b = 2;
two = (pack *)malloc(sizeof(pack));
two->a = 3, two->b = 4;
three = (pack *)malloc(sizeof(pack));
three->a = 5, three->b = 6;
d_ptr[0] = one;
d_ptr[1] = two;
d_ptr[2] = three;
// I can Only work-around below code (4 lines)
pack *t1 = d_ptr[1]; // For which index t1 would be assigned, is not known before hand
t1->a = 1; t1->b = 2;
printf("a: %d, b: %dn", two->a, two->b);
delete_me(t1); // How to delete t1 so that corresponding pointer also becomes NULL?
// Work around only till here was possible.
// Below this, No workaround possible.
if (two && (two->a == one->a)) // ASAN ERROR
printf("ERRORn");
else
printf("It works!n");
return 0;
}

ASAN错误:错误:AddressSanitizer:释放后堆使用

不幸的是,您的问题并不能真正解决。

当您有同一指针的多个副本时,例如

int *p1 = malloc(sizeof (int));
int *p2 = p1;
int *p3 = p2;

那么释放他们中的任何一个都会使所有人失效:

free(p2);
// Now p1, p2, p3 have invalid values.
// The C standard calls these "indeterminate values"; accessing them has undefined behavior

释放后,可以手动将p2设置为NULL,但这仍然会使p1p3悬空。您无法自动查找程序内存中任何位置可能存在的指针值的所有副本。

您需要重组程序的逻辑。没有简单快捷的解决办法。

相关内容

  • 没有找到相关文章

最新更新