我正在运行ASAN,目的是在一个非常大的项目中查找内存泄漏。我已找到原因,但不知道如何解决。我制作了一个示例程序来使问题易于理解。 在下面的程序中,我只能解决指定的代码。对于其余的代码,无法解决。 因此,请提出以下可能需要解决的解决方案:ASAN错误。 (如何使用t1将指针二设为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: %d\n", 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("ERROR\n");
else
printf("It works!\n");
return 0;
}
ASAN错误: 错误:AddressSanitizer:释放后使用堆
答案 0 :(得分:0)
不幸的是,您的问题并不能真正解决。
例如,同一指针有多个副本时,
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
,但这仍然使p1
和p3
悬空。您无法自动找到程序内存中任何地方可能存在的指针值的所有副本。
您需要重组程序的逻辑。没有快速简便的修复方法。