c++dictionarypointersmemcpy

Copying struct into one element of an array


In the code I am working on, I need to do the following:

  1. Create a map where each value is buffer of fixed size
  2. Use memcpy to populate one element of one value of the map (that is, one element of an array that is itself a value of the map) with some locally defined object

The following code is a small example of the concept:

#include <iostream>
#include <map>
#include <cstring>

int main()
{
    struct hdr {
        int cpi_length = 42;
    } ;

    void* this_hdr = new hdr;
    std::map<int, hdr(*)[20]> SP;
    std::cout << sizeof(hdr) << std::endl; // "4"
    std::cout << sizeof(this_hdr) << std::endl; // "4"
    std::cout << sizeof(SP[0][0]); // "80"
    std::memcpy(SP[0][0], this_hdr, sizeof(hdr)); // "Error: access violation"
    std::cout << SP[0][0]->cpi_length;
    return 0;
}

This brings me to two problems: 1) how to resolve the runtime error when trying to use memcpy, and 2) once the error is resolved, how do I ensure that this code will do what I described it should do?

As shown with the commands sizeof, the instance of the struct being copied in is identical in size to the struct itself, and (apparently) is a lot smaller than the size of the array element it is being copied into. So why the access violation? There should be plenty of room to spare.

I know that it may seem silly why I would use memcpy in this instance, why would I use pointers for the buffer instead of a vector, etc. This is just a reproducible example, understand that in the actual code I am restricted to these implementation choices. For now, I am going off of the assumption that I am just making some simple mistake like mixing up the syntax when it comes to referencing/de-referencing pointers.


Solution

  • Create a map where each value is buffer of fixed size

    That's not what you are doing. Here's the one test you forgot:

    std::cout << sizeof(SP[0]); // How large is the actual element of the map?
    

    Here's a map where each value is a buffer of a fixed size:

    std::map<int, std::array<hdr, 20>> SP;