为什么在以下代码中需要更多内存? [英] Why need more memory in following code?

查看:77
本文介绍了为什么在以下代码中需要更多内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"
#include "string.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
	typedef struct _NODE
	{
		int			iIndex;
		char		cData;
		bool		bFinal;			
		_NODE		*pNextNode;
	}NODE,*LPNODE;
		

	NODE	objRoot;
	NODE	*pNewNode = NULL, *pCurrentNode = NULL;	
	int		iDummy = 0x00;

	memset(&objRoot,0x00,sizeof(NODE));
	objRoot.bFinal = false;
	objRoot.iIndex = iDummy;
	objRoot.cData = 'a';
	objRoot.pNextNode = NULL;
	pCurrentNode = &objRoot;

	for(iDummy = 0x00; iDummy < 1000000; iDummy++)
	{
		pNewNode = (NODE *)calloc(0x01,sizeof(NODE));
		
		if (pNewNode)
		{
			pNewNode->iIndex = iDummy;
			pNewNode->bFinal = false;
			pNewNode->cData = 'a';
			pNewNode->pNextNode = NULL;

			pCurrentNode->pNextNode = pNewNode;
			pCurrentNode = pCurrentNode->pNextNode;

			
			
		}
		else
		{
			break;
		}
	}
	return 0;
}





我的尝试:


见进程资源管理器。



What I have tried:

after executing this code then need memory (Private Working Set) is 70800 K how is possible
see in process explorer.

推荐答案

for(iDummy = 0x00; iDummy < 1000000; iDummy++)



您正在分配一百万个节点,每个节点占用128个字节(在64位系统上为256个)。您期望什么?


You are allocating a million nodes each of which takes 128 bytes (256 on a 64 bit system). What do you expect?


结构占用12个字节,32位构建,可能20个字节,64位构建(尚未检查)。



但是必须也管理分配的内存。这至少需要存储地址,大小(或下一个块的地址)和标志(使用/免费)。使用调试版本时,通常会有额外的字节来检测缓冲区溢出。只有在检查相应的C标准库源代码时才能回答内存管理使用的字节数。



所以最终得到70.8 M已用内存为1 M项。您可以尝试使用不同的构建选项(32/64位,调试/发布,结构打包)来查看它如何影响内存使用情况。



你应该拥有什么了解到:

在堆上分配许多小块是低效的。
The structure occupies 12 bytes with 32-bit builds and probably 20 bytes with 64-bit builds (have not checked that).

But the allocated memory must be also managed. This requires at least storing the address, the size (or address of next block), and a flag (used / free). With debug builds there are usually additional bytes to detect buffer overruns. How many bytes are used by the memory management can be only answered when inspecting the corresponding C standard library source code.

So you ended up with 70.8 M used memory for 1 M items. You might try it with different build options (32/64 bit, debug/release, structure packing) to see how this affects the memory usage.

What you should have learned:
It is inefficient to allocate many small blocks on the heap.


您正面临内存碎片问题。你应该尝试最合适的内存管理..
You are facing problem of memory fragmentation. You should try with best-fit memory management..


这篇关于为什么在以下代码中需要更多内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆