【发布时间】:2020-12-28 05:01:55
【问题描述】:
我正在尝试了解 malloc 如何与指针等一起工作,并且我尝试释放指针内存,但是当我使用 valgrind 检查内存泄漏时,它仍然说我有 32 个字节可以访问。
#include <stdio.h>
#include <stdlib.h>
void fib2(int* a);
int main()
{
int *pointer;
//allocates space for 2 elements for pointer
pointer = malloc(100 * sizeof(int));
//prints first two fibonacci values
printf("0 1 ");
//calls fib2 func and apsses pointer into it
fib2(pointer);
//frees pointer memory
free(pointer);
printf("\n");
return 0;
}
//generates fibonacci sequence
void fib2(int* a)
{
int i;
//initial fibonacci array initialized
a[0] = 0;
a[1] = 1;
//generates and calculates fibonacci sequence and prints
for(i = 2; i < 12; i++)
{
a[i] = a[i - 1] + a[i - 2];
printf("%d ", a[i]);
}
}
**按照之前的要求以文本形式编辑 Valgrind 输出
==5451== Memcheck, a memory error detector
==5451== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5451== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==5451== Command: ./lab3
==5451== 0 1 1 2 3 5 8 13 21 34 55 89
==5451==
==5451== HEAP SUMMARY:
==5451== in use at exit: 32 bytes in 1 blocks
==5451== total heap usage: 50 allocs, 49 frees, 107,863 bytes allocated
==5451==
==5451== LEAK SUMMARY:
==5451== definitely lost: 0 bytes in 0 blocks
==5451== indirectly lost: 0 bytes in 0 blocks
==5451== possibly lost: 0 bytes in 0 blocks
==5451== still reachable: 32 bytes in 1 blocks
==5451== suppressed: 0 bytes in 0 blocks
==5451== Rerun with --leak-check=full to see details of leaked memory
==5451==
==5451== For counts of detected and suppressed errors, rerun with: -v
==5451== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
【问题讨论】:
-
您释放了指针。可能是
stdio使用的内部指针。 -
你的指针指向 400 字节,所以这不是警告信息所说的。
-
请edit你的问题并添加来自valgrind的输出作为文本。
-
但我的一般观点是正确的:它来自程序员无法控制的库,因此他们无能为力。