一 需求:
使用new操作测试程序最多可申请多大的堆内存
二 实现:
1.直接使用new
直接使用new可能会抛出bad_alloc异常,所以要使用try catch捕获
2.使用new(nothrow)
分配失败不会抛出异常,而是返回空指针
三 代码:
1.test.cpp
#include <stdint.h>
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <new>
using namespace std;
static const uint64_t ONE_G = 1024 * 1024 * 1024;
bool test_system_stack_memory(size_t size) {
char *p = nullptr;
uint64_t capacity = ONE_G * size;
bool succ = true;
try {
p = new char[capacity];
}
//catch (std::exception &e) {
catch (std::bad_alloc &e) {
succ = false;
cerr << e.what() << endl;
cerr << size << "G" << " alloc failed...!" << endl;
}
if (nullptr != p) {
delete []p;
p = nullptr;
}
return succ;
}
bool test_system_stack_memory1(size_t size) {
uint64_t capacity = ONE_G * size;
bool succ = true;
char *p = new(nothrow) char[capacity];
if (nullptr != p) {
delete []p;
p = nullptr;
}
else {
succ = false;
cerr << size << "G" << " alloc failed...!" << endl;
}
return succ;
}
int main() {
for (size_t i = 0;i < 1000;i++) {
// if (false == test_system_stack_memory(i)) { // 0.004s
if (false == test_system_stack_memory1(i)) { // 0.004s
return -1;
}
}
return 0;
}
2.make.sh
g++ -std=c++17 -g -o Test test.cpp -pthread
3.使用valgrind检查内存
check.sh
valgrind --tool=memcheck --leak-check=full ./Test
valgrind --tool=cachegrind ./Test