AndroidC++中使用new运算符导致“malloc(4294967295)失败,errno12”
创始人
2024-10-06 14:47:01
0

这个错误通常是由于请求分配的内存太大而导致的。在32位系统上,这意味着分配了超过4GB的内存,超出了系统的限制。解决方法是使用分段内存分配,或者减少所需的内存量。

以下是一个简单的示例,演示如何使用分段内存分配:

#include 
#include 

using namespace std;

const int CHUNK_SIZE = 1024 * 1024; // 每个块的大小为1MB

class MemoryPool
{
public:
    MemoryPool(int blockSize, int chunkSize) : blockSize(blockSize), chunkSize(chunkSize)
    {
        head = 0;
    }

    ~MemoryPool()
    {
        for (int i = 0; i < blocks.size(); ++i)
        {
            free(blocks[i]);
        }
    }

    void* allocate()
    {
        if (head == 0)
        {
            expand();
        }

        void* ptr = reinterpret_cast(chunks[head - 1] + (blockSize * (chunkSize - 1)));
        --head;

        return ptr;
    }

    void deallocate(void* ptr)
    {
        int chunk = ((reinterpret_cast(ptr) - chunks[0]) / blockSize) / chunkSize;

        if (chunk >= head && chunk < chunkSize)
        {
            head = chunk + 1;
        }
    }

private:
    void expand()
    {
        void* buffer = malloc(blockSize * chunkSize);
        chunks.push_back(reinterpret_cast(buffer));

        for (int i = 0; i < chunkSize; ++i)
        {
            void* ptr = reinterpret_cast(reinterpret_cast(buffer) + (blockSize * i));
            freeList.push(ptr);
        }

        head = chunkSize;
        blocks.push_back(buffer);
    }

    int blockSize;
    int chunkSize;
    vector chunks;
    vector blocks;
    int head;
    queue freeList;
};

MemoryPool pool(sizeof(int), CHUNK_SIZE);

int* createIntArray(int size)
{
    int* array = reinterpret_cast(pool.allocate());

    for (int i = 0; i < size; ++i)
    {
        array[i] = 0;
    }

    return array;
}

void deleteIntArray(int* array)
{
    pool.deallocate(array);
}

int main()
{
    int* array1 = createIntArray(1024 * 1024 * 4); // 申请4MB内存
    int* array2 = createIntArray(1); // 申请1个int类型的内存
    deleteIntArray(array1);
    deleteIntArray(array2);

    return 0;
}

上述示例中,使用了一个名为MemoryPool的类,用于分配和释放内存。该类使用了两个std::vector,其中一个存储所有的内存块,另一个存储所有未使用的指针。每次调用allocate()方法时,该方法会检查freelist是否包含未使用的指针,如果有,则返回指针。如果freelist为空,则扩展内存块。在调用deallocate()方法时,会将指针返回给freelist。

使用MemoryPool类可避免在32位系统上分配过多内存而导致的

相关内容

热门资讯

安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
oppo手机安卓系统换成苹果系... OPPO手机安卓系统换成苹果系统:现实吗?如何操作?随着智能手机市场的不断发展,用户对于手机系统的需...
安卓平板改windows 系统... 你有没有想过,你的安卓平板电脑是不是也能变身成Windows系统的超级英雄呢?想象在同一个设备上,你...
iphone系统与安卓系统更新... 最近是不是你也遇到了这样的烦恼?手机更新系统总是失败,急得你团团转。别急,今天就来给你揭秘为什么iP...
安卓系统上滑按键,便捷生活与高... 你有没有发现,现在手机屏幕越来越大,操作起来却越来越方便了呢?这都得归功于安卓系统上的那些神奇的上滑...
安卓系统连接耳机模式,蓝牙、有... 亲爱的手机控们,你们有没有遇到过这种情况:手机突然变成了“耳机模式”,明明耳机没插,声音却只从耳机孔...
希沃系统怎么装安卓系统,解锁更... 亲爱的读者们,你是否也像我一样,对希沃一体机上的安卓系统充满了好奇呢?想象在教室里,你的希沃一体机不...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
安卓换鸿蒙系统会卡吗,体验流畅... 最近手机圈可是热闹非凡呢!不少安卓用户都在议论纷纷,说鸿蒙系统要来啦!那么,安卓手机换上鸿蒙系统后,...