gpt4 book ai didi

c++ - 即使还有足够的内存,内存分配也失败

转载 作者:IT王子 更新时间:2023-10-29 01:23:12 27 4
gpt4 key购买 nike

我在 Linux(正好是 ubuntu 13.04)上工作,目前我有一个问题:为什么即使内存仍然足够,内存分配也会失败?

我今天写了一个简单的测试应用程序,在运行这个测试应用程序时遇到了这个问题。下面是我用来测试的代码片段:

     #include <stdio.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <strings.h>

using namespace std;
unsigned short calcrc(unsigned char *ptr, int count)
{
unsigned short crc;
unsigned char i;

//high cpu-consumption code
//implements CRC algorithm: Cylic
//Redundancy code
}


void* CreateChild(void* param){
vector<unsigned char*> MemoryVector;
pid_t PID = fork();
if (PID == 0){
const int MEMORY_TO_ALLOC = 1024 * 1024;
unsigned char* buffer = NULL;
while(1){
buffer = NULL;
try{
buffer = new unsigned char [MEMORY_TO_ALLOC]();
calcrc(buffer, MEMORY_TO_ALLOC );
MemoryVector.push_back(buffer);
} catch(...){
printf("an exception was thrown!\n");
continue;
} //try ... catch
} //while
} // if pid == 0

return NULL;
}

int main(){
int children = 4;
while(--children >= 0){
CreateChild(NULL);
};

while(1) sleep(3600);
return 0;
}

在我的测试中,当有大约 220M RAM 可用 时,上述代码开始抛出异常。从现在开始,应用程序似乎无法再获得更多内存因为 TOP 命令显示的空闲内存仍然在 210M 以上。那为什么会这样呢?

更新
1.软硬件信息
RAM 为 4G,交换空间约为 9G 字节。运行“uname -a”给出:Linux steve-ThinkPad-T410 3.8.0-30-generic#44-Ubuntu SMP Thu Aug 22 20:54:42 UTC 2013 i686 i686 i686 GNU/Linux< br/>2.测试期间的统计数据

      Right after Test App Starts Throwing Exception
steve@steve-ThinkPad-T410:~$ free
total used free shared buffers cached
Mem: 3989340 3763292 226048 0 2548 79728
-/+ buffers/cache: 3681016 308324
Swap: 9760764 9432896 327868

10 minutes after Test App Starts Throwing Exception
steve@steve-ThinkPad-T410:~$ free
total used free shared buffers cached
Mem: 3989340 3770808 218532 0 3420 80632
-/+ buffers/cache: 3686756 302584
Swap: 9760764 9436168 324596


20 minutes after Test App Starts Throwing Exception
steve@steve-ThinkPad-T410:~$ free
total used free shared buffers cached
Mem: 3989340 3770960 218380 0 4376 104716
-/+ buffers/cache: 3661868 327472
Swap: 9760764 9535700 225064

40 minutes after Test App Starts Throwing Exception
steve@steve-ThinkPad-T410:~$ free
total used free shared buffers cached
Mem: 3989340 3739168 250172 0 2272 139108
-/+ buffers/cache: 3597788 391552
Swap: 9760764 9556292 204472

最佳答案

可能是您的地址空间中没有更多的 1MB 连续内存页。您有可用空间碎片。

关于c++ - 即使还有足够的内存,内存分配也失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18921187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com