繁体   English   中英

当仍有可用内存时,为什么deque :: pushback无法分配?

[英]Why does deque::pushback fail to allocate when there is still memory available?

我在具有16GB RAM的计算机上运行64位Windows 7,但是执行以下代码时:

#include <deque>
#include <iostream>

using namespace std;

struct Packet
{
    unsigned char* m_buffer;
    int m_bufferSize;

public:
    Packet() :
        m_buffer(nullptr),
        m_bufferSize(0)
    {

    }

    Packet(const Packet& rhs) :
        m_buffer(new unsigned char[rhs.m_bufferSize]),
        m_bufferSize(rhs.m_bufferSize)
    {
        memcpy(m_buffer, rhs.m_buffer, m_bufferSize);
    }

    Packet(unsigned char* newBuffer, unsigned int bufferSize) :
        m_buffer(new unsigned char[bufferSize]),
        m_bufferSize(bufferSize)
    {
        memcpy(m_buffer, newBuffer, bufferSize);
    }

    ~Packet()
    {
        delete[] m_buffer;
        m_buffer = nullptr;
    }

    unsigned char* Buffer()
    {
        return m_buffer;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    deque<Packet> d;

    const int PacketSize = 1051;
    unsigned char* buf = new unsigned char[PacketSize];
    memset(buf, 0, PacketSize);

    const unsigned long FileSize = 2.5 * 1000 * 1000 * 1000;
    const unsigned long MaxAllocations = FileSize / PacketSize; // Simulate buffering a 2.5GB file

    cout << "Simulating loading " << FileSize << " bytes in " << PacketSize << " byte chunks" << endl;
    cout << "Max deque size: " << d.max_size() << endl;
    cout << "Allocations to attempt: " << MaxAllocations << endl;

    for (int i = 0; i < MaxAllocations; ++i)
    {
        Packet p(buf, PacketSize);
        try
        {
            d.push_back(p);
        }
        catch (...)
        {
            cout << "Failed to allocate after " << i + 1 << " attempts" << endl;
            break;
        }
    }

    return 0;
}

我得到这个:

Simulating loading 2500000000 bytes in 1051 byte chunks
          Max deque size: 536870911
  Allocations to attempt: 2378686
Failed to allocate after: 1901555 attempts

Windows任务管理器建议仍然有足够的可用内存:

在此处输入图片说明

那为什么失败了?

Win32环境具有32位地址空间和2Gb硬进程分配限制。
为x64编译的相同代码可以正常运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM