jeudi 28 juillet 2016

Dynamic allocation of std::vector throws std::out_of_range [duplicate]

This question already has an answer here:

I am starting to learn about std::vector for a real-time application and I want to store my elements in the heap along with the header of the vector, when I use malloc I have got an exception:

"terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check."

However, when I use NEW it works just fine. Having said this, I have two questions: 1.Could anyone provide some hints on what is going on with malloc? and 2. I wonder if knowing that vector uses dynamic memory allocation already, what would be a good practice when using vectors? I want that my called functions see my vector without the need of returning pointers. In my RT application I need vectors of 1023 elements that will be converted in complex numbers for FFT calculations.

Thanks a lot.

#include <stdlib.h>
//#include <array>
#include <vector>

int main()
{

    std::vector<int>* pVec = (std::vector<int>*)malloc(5*sizeof(std::vector<int>));// this does not work.
    //std::vector<int> * pVec= new std::vector<int>(5); // this works

    std::vector<int> B= {2,4,1,6,9};

    for (int j=0;j<5;j++){
        (*pVec).at(j) = B.at(j);
        printf("%d ",pVec->at(j));
    }
    free(pVec);
    return 0;

}

Aucun commentaire:

Enregistrer un commentaire