Lucas
Lucas

Reputation: 3725

Copying a pointer

I'm sending some data through the network from the client <> server. I'm reading a packet without any issues, though I can not copy a SimpleTestPacket pointer for some reason. I have tried using memset where I am getting a segmentation fault.

Code:

typedef struct simpleTestPacket_t {
    uint32_t type;
    uint8_t point;
    int32_t value;
} SimpleTestPacket;

void onReceivePacket(uint8_t header, const char* data, size_t count) {
    const SimpleTestPacket* packet = reinterpret_cast<const SimpleTestPacket*> (data);

    SimpleTestPacket* independentPacket = nullptr;
    memset(independentPacket, packet, sizeof(SimpleTestPacket) * count);
}

How can I copy the packet pointer to the independentPacket variable so I could store it for a later-use? Would it be possible to make a copy without allocating a new memory which I would have to delete later?

Upvotes: 1

Views: 86

Answers (1)

Baum mit Augen
Baum mit Augen

Reputation: 50111

Just drop the unnecessary pointer business, make a local copy and deal with that:

const SimpleTestPacket* packet = 
         reinterpret_cast<const SimpleTestPacket*> (data);

auto independentPacket = *packet;

Now independentPacket is a local copy of packet with automatic storage duration.

Upvotes: 8

Related Questions