gpt4 book ai didi

c - 免费后使用ASAN堆

转载 作者:行者123 更新时间:2023-12-04 10:33:55 25 4
gpt4 key购买 nike

我正在运行 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: %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:heap-use-after-free

最佳答案

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

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

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

您可以手动设置 p2NULL释放后,但仍然留下 p1p3悬空。您无法自动找到可能存在于程序内存中任何位置的指针值的所有副本。

您需要重构程序的逻辑。没有快速简便的修复方法。

关于c - 免费后使用ASAN堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com