首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

问下 建链表会不会造成大量内存碎片解决办法

2012-03-28 
问下 建链表会不会造成大量内存碎片如果我定义链表struct a{int nstruct *next}如果我需要建立一个几亿

问下 建链表会不会造成大量内存碎片
如果我定义链表
struct a{
  int n;
  struct *next;
};
如果我需要建立一个几亿级别的链表,会不会造成大量的内存碎片
有没有比较好的方法

我想写个内存修改器,需要记录搜索的内存地址

[解决办法]
怎样试啊??大神说明一下可以吗??真心不懂
[解决办法]
底层的东西咱就别管啦,操作系统会有效利用内在,尽量避免内存碎片
内存池简单实现http://blog.csdn.net/yafeng_jiang/article/details/6991840
[解决办法]
内存碎片又分为内部碎片和外部碎片

Internal fragmentation occurs when an allocated block is larger than the payload. This might happen for a number of reasons. For example, the implementation of an allocator might impose a minimum size on allocated blocks that is greater than some requested payload.
Internal fragmentation is straightforward to quantify. It is simply the sum of the differences between the sizes of the allocated blocks and their payloads. Thus, at any point in time, the amount of internal fragmentation depends only on the pattern of previous requests and the allocator implementation

External fragmentation is much more difficult to quantify than internal fragmentation because it depends not only on the pattern of previous requests and the allocator implementation, but also on the pattern of future requests.
[解决办法]
new然后delete多了 肯定会有很多内存碎片的 如果先知道很多 自己可以预先分配 建立内存池管理
[解决办法]
首先链表在内存中不是连续存储的,当你不断申请释放内存的情况下,会出现内存碎片。
[解决办法]
肯定会的,这个问题,可以随便找一本操作系统原理,里面看看系统内存管理就会发现,对于大项目,(尤其是频繁内存操作的高性能项目),系统的内存管理功能不那么好使的。当然,对于一些自带内存管理功能的语言来说,在一定程度上,另当别论。

对于你所说的情况,建议在系统启动时候,分配足够多的内存,然后自己管理。最简单的情况,当然是假设你的链表中,每个节点,内存大小需求一致了。

对于这种理想情况,我给出一种方法:
写一个内存管理类,
类中有几个关键变量:start(内存起始),end(内存结束),这两个变量在系统初始化时候向OS申请的大内存决定。那么既然每个节点大小一样,就可以把这段内存想象成N个节点的一个连续表。这个表中有两类块,一类是已经被用得,另一类是当前可用的。
此外,你得迅速找到当前可用的块的位置。
我有一种像法师这样的:在这个类里有两个链表,一个当前可用链表,里面有当前可用的所有节点,一个当前正在使用链表,里面挂着所有当前已经被使用的节点。在初始化时候,当前可用节点,里面顺序存着从start到end的每一个块。
分配算法,从当前可用链表中摘一个节点,挂入当前正在使用链表。然后你程序获得这个节点之后,就获得了,对应地址的内存指针。
释放算法,清零该节点内存,然后将其挂入当前可用链表里。

分配复杂度O(1)。对于释放,性能也可以提高。可以在类分配节点中给出信息节点首地址。那么当你需要释放的时候,你就立刻可以知道,当前你要摘除的节点的位置。
[解决办法]
首先链表在内存中不是连续存储的,其次当你不断地分配和释放内存后会造成内存碎片。
好像克服这种问题的方法就是用内存池,你自己首先分配一块连续的内存,在内存中进行操作。
[解决办法]
仅供参考

C/C++ code
//使用动态分配#include <stdio.h>#include <stdlib.h>#include <malloc.h>int i,L;char *p;void main() {    for (i=0;i<20000;i++) {        L=rand();        p=malloc(L);        if (NULL==p) {            printf("malloc error!\n");            continue;        }        memset(p,0,L);        free(p);    }}//不使用动态分配#include <stdio.h>#include <stdlib.h>#include <memory.h>#define MAXLEN 30000int i,L;char buf[MAXLEN];char *p;void main() {    p=&buf[0];    for (i=0;i<20000;i++) {        L=rand();        if (L>MAXLEN) {            printf("L>MAXLEN==%d, ignore spilth.\n",MAXLEN);            L=MAXLEN;        }        memset(p,0,L);    }} 

热点排行