【发布时间】:2023-03-23 11:35:02
【问题描述】:
我有一个二次多项式系数的结构。我声明了一个这种结构类型的变量,我读取了系数的值,然后我创建并初始化了一个指向这个结构的指针。然后,我使用我的结构和指向结构变量的指针显示系数的值。最后,我将指向 struct 的指针设置为 NULL 并释放它。
但是,valgrind 检测到内存泄漏,我终其一生都无法理解原因。你能帮我理解吗?
valgrind ./polynome --leak-check=full
==11046== Memcheck, a memory error detector
==11046== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==11046== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==11046== Command: ./polynome --leak-check=full
==11046==
2 3 4
pCoeff: a = 2.000000, b = 3.000000, c = 4.000000
coeff: a = 2.000000, b = 3.000000, c = 4.000000
==11046==
==11046== HEAP SUMMARY:
==11046== in use at exit: 24 bytes in 1 blocks
==11046== total heap usage: 1 allocs, 0 frees, 24 bytes allocated
==11046==
==11046== LEAK SUMMARY:
==11046== definitely lost: 24 bytes in 1 blocks
==11046== indirectly lost: 0 bytes in 0 blocks
==11046== possibly lost: 0 bytes in 0 blocks
==11046== still reachable: 0 bytes in 0 blocks
==11046== suppressed: 0 bytes in 0 blocks
==11046== Rerun with --leak-check=full to see details of leaked memory
==11046==
==11046== For counts of detected and suppressed errors, rerun with: -v
==11046== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
这是我的 C 程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double a;
double b;
double c;
} Coefficient;
int main() {
Coefficient *pCoeff = NULL;
Coefficient coeff;
scanf("%lf %lf %lf", &coeff.a, &coeff.b, &coeff.c);
pCoeff = (Coefficient *)malloc(sizeof(Coefficient));
if (pCoeff == NULL) {
fprintf(stderr, "Memory allocation error.\n");
exit(1);
}
pCoeff = &coeff;
printf("pCoeff: a = %lf, b = %lf, c = %lf\n", pCoeff->a, pCoeff->b, pCoeff->c);
printf(" coeff: a = %lf, b = %lf, c = %lf\n", coeff.a, coeff.b, coeff.c);
pCoeff = NULL;
free(pCoeff);
return 0;
}
【问题讨论】:
-
你必须先释放指针。然后将其设置为 NULL。
-
@MartinZabel:如果我在释放之前没有将指针设置为 NULL,则会出现双重释放或损坏错误(因为它仍然指向 coeff 变量的地址)。跨度>
-
@user3121023:是的,我只是想在使用结构的动态分配中测试
int var = 3; int *p = &var;的等价物,我对为什么会出现内存泄漏感到困惑。还是你的意思是说我不应该那样做? -
我认为我应该使用 &coeff=NULL;免费(pCoeff);
-
@ganchito55:不,它不能工作,因为你不能在分配的左侧有地址运算符。
标签: c pointers struct memory-leaks