加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – `std :: vector`在调整大小时抛出“错误分配”异常

发布时间:2020-12-16 07:07:54 所属栏目:百科 来源:网络整理
导读:我在C dll中有以下代码,我通过JNI调用它: std::vectordouble myVector;myVector.resize(10000000,0); 我得到一个“错误的分配”异常,即使向量的最大大小应该大于10000000. 我应该使用什么工具来跟踪内存分配,以便找到任何内存泄漏? 如果确实没有内存泄漏,
我在C dll中有以下代码,我通过JNI调用它:

std::vector<double> myVector;
myVector.resize(10000000,0);

我得到一个“错误的分配”异常,即使向量的最大大小应该大于10000000.

我应该使用什么工具来跟踪内存分配,以便找到任何内存泄漏?

如果确实没有内存泄漏,我怎样才能减少向量的占用空间以确保我有足够的空间?

解决方法

我知道这可能是找出你的分配大小的最糟糕的解决方案.所以这里:

main.cpp中:

#include "jni.h"
#include <vector>
#include <iostream>

#if (_MSC_VER == 1800) || (__cplusplus >= 201103L)
    #include <thread>
    #include <chrono>
#elif _MSC_VER
    #include <windows.h>
#else
    #include <unistd.h>
#endif


extern "C" JNIEXPORT void Java_test_Test_Alloc(JNIEnv* env,jobject obj,jint max_size,jint increment_size)
{
    std::vector<double> vec;
    size_t isize = max_size / 4;
    size_t oldsize = isize;

    while(isize <= max_size)
    {
        try
        {
            vec.resize(isize,0);
            oldsize = isize;
            isize += increment_size;
            std::cout<<"Allocated: "<<vec.size() * sizeof(double)<<" bytes.n";
        }
        catch (std::bad_alloc &e)
        {
            std::cout<<"Failed to allocate: "<<isize * sizeof(double)<<" bytes.n";
            std::cout<<"Approx. max size: "<<oldsize * sizeof(double)<<" bytes.n";
            std::cout<<"Exception: "<<e.what()<< "n";
            std::cout<<"Vector.Max_Size(): "<<vec.max_size()<< "n";
            break;
        }

        #if (_MSC_VER == 1800) || (__cplusplus >= 201103L)
            std::this_thread::sleep_for(std::chrono::seconds(1));
        #elif _MSC_VER
            Sleep(1);
        #else
            sleep(1);
        #endif
    }
}

#if defined _WIN32 || defined _WIN64
#include <windows.h>

extern "C" __declspec(dllexport) bool __stdcall DllMain(HINSTANCE hinstDLL,unsigned fdwReason,void* lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            break;

        case DLL_PROCESS_DETACH:
            break;
    }
    return true;
}
#endif

而在Java方面(Test.java):

package test;

public class Test {

    static {
        System.loadLibrary("JNITest");
    }

    public static native void Alloc(int max_size,int increment_size);

    public static void main(String[] args) {
        Alloc(100000000,50000);
    }

}

对我来说,它打印:

Allocated: 200000000 bytes.
Allocated: 200400000 bytes.
Allocated: 200800000 bytes.
.
.
.
Allocated: 399600000 bytes.
Allocated: 400000000 bytes.
Failed to allocate: 400400000 bytes.
Approx. max size: 400000000 bytes.
Exception: std::bad_alloc
Vector.Max_Size(): 536870911

就像我说的那样..这是一个“猜测”你可以分配多少的坏方法,但在这种情况下,没有其他人发布任何东西,所以我将把它留在这里,如果你愿意,你可以使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读