In the code I am working on, I need to do the following:
- Create a map where each value is buffer of fixed size
- 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.
SP[0]is a pointer to an array of 20hdrs. Here's a trick question for you: in the shown code, where doesSP[0]actually point to? This is a trick question because it's not pointing to anywhere. The shown code fails to initialize this pointer, soSP[0][0]results in demons flying out of your nose. You need to figure out where this should be pointing to, and adjust the code accordingly.hdr*. OP has one uninitializedd pointer.