#include<stdio.h>#include<stdlib.h>intmain() {
int* arr;
int n = 5;
arr = (int*)malloc(n *sizeof(int));
if(arr ==NULL){
printf("内存分配失败!\n");
return-1;
}
for(int i = 0; i < n; i++){
arr[i]= i +1;
}
// 没有释放内存return0;
}
执行结果:
==12345==Memcheck,amemoryerrordetector==12345==Copyright(C)2002-2017,andGNUGPL'd,byJulianSewardetal.==12345==UsingValgrind-3.13.0andLibVEX;rerunwith-hforcopyrightinfo==12345==Command:program==12345====12345==HEAP SUMMARY:==12345==in use at exit:20bytesin1blocks==12345==total heap usage:1allocs,0frees,20bytesallocated==12345====12345==20bytesin1blocksaredefinitelylostinlossrecord1of1==12345==at 0x4C2FB0F:malloc(in/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)==12345==by 0x108688:main(program.c:8)==12345====12345==LEAK SUMMARY:==12345==definitely lost:20bytesin1blocks.==12345==indirectly lost:0bytesin0blocks.==12345==possibly lost:0bytesin0blocks.==12345==still reachable:0bytesin0blocks.==12345==suppressed:0bytesin0blocks.==12345====12345==Forcountsofdetectedandsuppressederrors,rerun with:-v==12345==ERROR SUMMARY: 1 errors from 1 contexts (suppressed:0from0)
分析:
Valgrind 检测到程序存在内存泄漏,泄漏了 20 字节的内存。
5.2 修复内存泄漏
修复内存泄漏的方法是使用 free 函数释放已动态分配的内存。
修复后的示例:
#include<stdio.h>#include<stdlib.h>intmain() {
int* arr;
int n = 5;
arr = (int*)malloc(n *sizeof(int));
if(arr ==NULL){
printf("内存分配失败!\n");
return-1;
}
for(int i = 0; i < n; i++){
arr[i]= i +1;
}
free(arr);
return0;
}
执行结果:
==12345== Memcheck, a memory error detector
==12345== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12345== Using Valgrind-3.13.0and LibVEX; rerun with -h for copyright info
==12345== Command: program
==12345==
==12345== HEAP SUMMARY:
==12345== in use at exit: 0 bytes in0 blocks
==12345== total heap usage: 1 allocs, 1 frees, 20 bytes allocated
==12345==
==12345== All heap blocks were freed -- no leaks are possible
==12345==
==12345== For counts of detected and suppressed errors, rerun with: -v
==12345== ERROR SUMMARY: 0 errors from0 contexts (suppressed: 0from0)
分析:
修复后的程序使用 free 函数释放了已动态分配的内存,Valgrind 检测到没有内存泄漏。
六、总结
通过本文的学习,我们掌握了 C 语言内存管理与动态内存分配的方法,包括动态内存分配函数(malloc、calloc、realloc、free)的使用方法,以及动态内存分配导致的错误(内存泄漏、内存越界、重复释放内存、使用已释放的内存)。我们还学习了如何使用工具检测内存泄漏,并修复内存泄漏。