c++ 系统内存检查(Linux)

c++ 系统内存检查(Linux),第1张

c++ 系统内存检查(Linux)

文章目录
    • c++ 系统内存检查(Linux)
      • 检查内存泄露
      • 检查堆溢出
      • 检查栈溢出
      • 检查全局内存溢出
      • 检查释放后继续使用

检查内存泄露

通过g++来检查内存泄露的问题

# g++
g++ -fsanitize=address -g -o testmen testmem.cpp
# CMakeLists.txt 里面添加
set(CMAKE_CXX_FLAGS "-fsanitize=address")

使用-fsanitize=address开关以后,代码不用做任何改动,就自动具有报告内存泄漏的能力

// 示例代码
#include 
#include 
#include 

using namespace std;

void new_test()
{
	int *test = new int[80];
}
void malloc_test()
{
	int *test =(int*) malloc(100);
}

int main()
{
    cout << "memory test" << endl;
	malloc_test();
	cout << "malloc test end" << endl;

	new_test();
	cout << "new test end" << endl;

	return 0;
}

gcc 4.8以上的版本内嵌有该功能,如果在编译链接时出现错误提示:“/usr/bin/ld:找不到/usr/lib64/libasan.so.5.0.0”,则需要安装libasan

ASan(Address Sanitizer)是一个C/C++内存错误检测器,它可以发现很多内存相关的错误,比如内存泄漏、释放之后再次使用、堆内存溢出、栈溢出等

检查堆溢出
// 示例代码
void heap_buffer_overflow_test()
{
	char *test = new char[10];
	const char* str = "this is a test string";
	strcpy(test,str);
	delete []test;
}
检查栈溢出
// 示例代码
void heap_buffer_overflow_test()
{
	char *test = new char[10];
	const char* str = "this is a test string";
	strcpy(test,str);
	delete []test;
}
检查全局内存溢出
// 示例代码
int global_data[100] = {0};
void global_buffer_overflow_test()
{
	int data = global_data[101];
}
检查释放后继续使用
// 示例代码
void use_after_free_test()
{
	char *test = new char[10];
	strcpy(test,"this test");
	delete []test;
	char c = test[0];
}

注意:
添加了-fsanitize=address选项后,不能再用valgrind -v来查看内存泄露

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/567239.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存