C/C++内存泄漏及检测 #include <crtdbg.h>

根据关键字“内存检测”,可以搜到很多相关工具。

C/C++内存泄漏及检测

http://www.cnblogs.com/skynet/archive/2011/02/20/1959162.html

该篇帖子,只要在程序中加入一些调试语句,当然仅适合在VC环境中。

经测试,

_CrtDumpMemoryLeaks()

似乎只能定位malloc,而不能定位new。


贴上测试代码(开发环境:Visual Studio 2008):

//工具+选项+文本编辑器+(C++)+常规 ->行号

#define _CRTDBG_MAP_ALLOC
#include "stdlib.h"
#include "crtdbg.h"
 
#include <iostream>
using namespace std;

int* getInt() {
	int* p = (int*)malloc(sizeof(int));
	*p = 100;
	return p;
}
 
char* GetMemory(char *p, int num)
{
    p = (char*)malloc(sizeof(char) * num);
	return p;
}
 
int main(int argc,char** argv)
{
    char *str = NULL;
    char *p = GetMemory(str, 100);
	free(p);
    cout<<"Memory leak test!"<<endl;

	int* pInt = getInt();
	cout << *pInt << endl;
	free(pInt);

    _CrtDumpMemoryLeaks();
    return 0;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
修改后的代码如下: ```c #include <stdio.h> #include <stdlib.h> #include <math.h> #include <crtdbg.h> #include <corecrt_malloc.h> #include <string.h> #include <queue> using namespace std; struct node { int data; struct node* left; struct node* right; }; struct node* createNode(int val) { struct node* newNode = (struct node*)malloc(sizeof(struct node)); newNode->data = val; newNode->left = NULL; newNode->right = NULL; return newNode; } struct node* constructBinaryTree(int N) { struct node* root; queue<struct node*> tree; if (N == 4) { root = createNode(0); root->left = createNode(N); root->right = createNode(0); return root; } int left = 1, right = N - 1; while (right >= 5) { struct node* right_tree = constructBinaryTree(right); root = createNode(0); root->left = createNode(left); root->right = createNode(right); root->right->left = right_tree; tree.push(root); left += 1; right -= 1; } return tree.front(); } int process(struct node* root) { int ans = 0; if (root->left == NULL && root->right == NULL) return 0; if (root->left != NULL) ans += process(root->left) + root->left->data + ((root->left->data + 1) * root->left->data) / 2; if (root->right != NULL) ans += process(root->right) + root->right->data + ((root->right->data + 1) * root->right->data) / 2; return ans; } int main() { int N = 22; int ans = 0; struct node* root = constructBinaryTree(N); ans = process(root); printf("%d", ans); return 0; } ``` 修改的地方: 1. 删除了无用的头文件。 2. 在 `constructBinaryTree` 函数中增加了 `queue` 的定义和使用,用于存储二叉树的节点。 3. 在 `main` 函数中,将 `ans` 的初始化放在了定义中。 4. 最后,增加了 `return 0;` 语句,用于指示程序正常结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值