GDB调试之内存检查(二十二)

一、内存泄漏检测

内存泄漏检测常用命令:

  • call malloc_stats()
  • call malloc_info(0, stdout)

调试代码如下所示:

#include <malloc.h>
#include <string.h>
#include <thread>
#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
using namespace std;

void test_malloc_leak(int size)
{
	malloc(1024);
}
void no_leak()
{
	void *p=malloc(1024*1024*10);
	free(p);
}
int main(int argc,char* argv[])
{
	no_leak();
	test_malloc_leak(1024);
	return 0;
}

call malloc_stats()的使用:

call malloc_info(0, stdout)函数的使用:

二、内存检查

gcc选项 -fsanitize=address:

  • 检查内存泄漏
  • 检查堆溢出
  • 检查栈溢出
  • 检查全局内存溢出
  • 检查释放后再使用

调试代码如下所示:

#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
void new_test()
{
	int *test = new int[80];
	test[0]=0;
}
void malloc_test()
{
	int *test =(int*) malloc(100);
	test[0]=0;
}
void heap_buffer_overflow_test()
{
	char *test = new char[10];
	const char* str = "this is a test string";
	strcpy(test,str);
	delete []test;

}
void stack_buffer_overflow_test()
{
	int test[10];
	test[1]=0;
	int a = test[13];
	cout << a << endl;

}
int global_data[100] = {0};
void global_buffer_overflow_test()
{
	int data = global_data[102];
	cout << data << endl;

}
void use_after_free_test()
{
	char *test = new char[10];
	strcpy(test,"this test");
	delete []test;
	char c = test[0];
	cout << c << endl;
}
int main()
{
	//new_test();
	//malloc_test();
	
	//heap_buffer_overflow_test();
	
	//stack_buffer_overflow_test();
	//global_buffer_overflow_test();
	use_after_free_test();
	
	return 0;
}

一旦在运行过程中出现内存泄漏的问题,就会把详细信息打印出来

  

 
posted @ 2024-01-23 15:53  TechNomad  阅读(186)  评论(0编辑  收藏  举报