Adam Barret
Adam Barret

Reputation: 11

Allocate memory for a pointer to vector of structs

I have a structure PWS:

struct PWS{
    uint64_t key;
    char* value;
    uint64_t timestamp;
    uint64_t txn_id;
};

I want to create a pointer to a vector of PWS to populate it later in my code. Is this way correct?

int total_no_of_items = 100000;
vector<PWS> * pws = (vector<PWS>*) _mm_malloc(sizeof(vector<PWS>*) * total_no_of_items, 0);

Upvotes: 0

Views: 151

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72469

Unfortunately this is incorrect. You are allocating 100000 uninitialized pointers to vector<PWS>, not a vector of structs. If you want to allocate a vector of structs that would be as simple as:

vector<PWS> pws(total_no_of_items);

If you want the vector itself be heap-allocate (for whatever strange reason), then that would be:

unique_ptr<vector<PWS>> pws(new vector<PWS>(total_no_of_items));

Also it's unclear why you're trying to use _mm_malloc. If your goal is to load your struct with some SIMD instructions, then you should specify the alignment on the struct:

struct alignas(16) PWS { ... }; // aligned for xmm

std::vector's allocator will take care of the rest.

Upvotes: 1

Related Questions