簡體   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