前言
本次测试包括,检测无误的代码,检测内存泄漏,检测访问越界,检测野指针,检测访问已经释放(已经被free)的内存。
一 安装valgrind
sudo apt install valgrind
二 无错误
#include <stdio.h>
#include <stdlib.h>#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#define DEBUG_INFO(format, ...) printf("%s:%d $$ " format "\n" \
,__func__,__LINE__ \
, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endifint main(int argc, char **argv){char *p = (char*)malloc(sizeof(char));*p = 0x31;DEBUG_INFO("p = %c", *p);return 0;
}
测试:
二 malloc内存未释放
注释掉前面代码的free
#include <stdio.h>
#include <stdlib.h>#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#define DEBUG_INFO(format, ...) printf("%s:%d $$ " format "\n" \
,__func__,__LINE__ \
, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endifint main(int argc, char **argv){char *p = (char*)malloc(sizeof(char)*10);*p = 0x31;DEBUG_INFO("p = %c", *p);//free(p);return 0;
}
三 越界访问malloc分配的内存
#include <stdio.h>
#include <stdlib.h>#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#define DEBUG_INFO(format, ...) printf("%s:%d $$ " format "\n" \
,__func__,__LINE__ \
, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endifint main(int argc, char **argv){int *p = (int*)malloc(sizeof(int) * 5);p[6] = 20;DEBUG_INFO("value = %c", p[6]);free(p);return 0;
}
四 使用野指针
#include <stdio.h>
#include <stdlib.h>#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#define DEBUG_INFO(format, ...) printf("%s:%d $$ " format "\n" \
,__func__,__LINE__ \
, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endifint main(int argc, char **argv){int index = 100;char *p ;//= (char*)malloc(sizeof(char)*10);*(p + index) = 0x31;DEBUG_INFO("p = %c", *(p + index));//free(p);return 0;
}
五 访问已经释放的内存
#include <stdio.h>
#include <stdlib.h>#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#define DEBUG_INFO(format, ...) printf("%s:%d $$ " format "\n" \
,__func__,__LINE__ \
, ##__VA_ARGS__)
#else
#define DEBUG_INFO(format, ...)
#endifint main(int argc, char **argv){int index = 100;char *p = (char*)malloc(sizeof(char)*10);free(p);*(p + index) = 0x31;DEBUG_INFO("p = %c", *(p + index));//free(p);return 0;
}