0

I have a char array that should be converted to a struct. I can't figure out how to fix memory error that my code is causing. Console is printing the expected result, however the program crashes at the end of main().

#include <iostream>
#include <map>

using namespace std;

struct lsa
{
    int id;
    int seqNum;
    map<int, int> neighbors;

    lsa()
    {
        id = 1;
        seqNum = 1;
    }

    friend ostream& operator<<(ostream& os, const lsa& a)
    {
        os << "id: " << a.id << ", seqNum: " << a.seqNum << ", # of neighbors: " << a.neighbors.size() << endl;
        return os;
    }
};

int main()
{
    lsa msg;
    msg.id = 4;
    msg.seqNum = 5;
    msg.neighbors.insert(make_pair(2, 2));
    msg.neighbors.insert(make_pair(3, 3));

    const int bufsize = 1024;
    char data[bufsize];
    memset(data, 0, bufsize);

    // turn LSA into bytes, that will be stored in "data"
    memcpy(data, &msg, sizeof(msg));

    // move data bytes to "out" LSA
    lsa out;
    memcpy(&out, &data, sizeof(data));

    cout << out << endl;
}
haosmark
  • 1,097
  • 2
  • 13
  • 27
  • 5
    `memcpy`ing a std::map is probably a very, very bad idea. Also, check how big `sizeof(data)` is. – Michael Albers Sep 25 '20 at 02:27
  • If you follow the above advice and check `sizeof(data)` you might as well check `sizeof(neighbors)` after adding one, two, and several elements. – JohnFilleau Sep 25 '20 at 02:33
  • 1
    If your struct is nothing but POD (plain old data), AND it's tightly packed (no padding), AND you're not sending your data to a different architecture, then `std::memcpy` is fine for serialization and deserialization. For anything more complicated, I write a serialization function that takes an iterator and copy elements item-by-item. POD in your struct can be `memcpy`'d, for a `std::map` I'd store it as an integer-type `size` field, followed by `size` number of pairs of `int`s for each data point. If another system will deserialize, I convert to big endian. Deserialization is opposite. – JohnFilleau Sep 25 '20 at 02:38
  • DDDDDDDD and other numbers that are too regular to be dumb luck often means the program's trying to [tell you something](https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values). – user4581301 Sep 25 '20 at 02:53
  • 0xDD means dead memory: [When and why will a compiler initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?](https://stackoverflow.com/q/370195/995714) – phuclv Sep 25 '20 at 03:58

0 Answers0