apmeyers1987
apmeyers1987

Reputation: 859

SEGFAULT when using memcpy to copy from buffer to array of structs

I have the following struct defined

typedef struct {
    uint16_t type;
    uint16_t name_offset;
    uint32_t data_offset;
    uint32_t size;
}node;

sizeof(node) returns 12 bytes as expected.

node *nodes = (node*)malloc(sizeof(node)*nodecount);

In my current test nodecount is 96 and the memory allocated for nodes is 1152 as expected. (tested via _msize)

I want to memcpy from a buffer I have at offset 20 into this new nodes array (this is where I crash). I have confirmed that 0x20(inclusive)-0x4A0(exclusive) is the correct structure for this array.

memcpy(nodes,buffer[0x20],sizeof(node)*nodecount)

Buffer looks like this

00000020: 01 00 00 00 00 00 00 00 00 00 00 60
...
00000490: 00 00 00 88 00 00 06 89 02 15 DE 40

Upvotes: 0

Views: 365

Answers (1)

user2736738
user2736738

Reputation: 30926

The correct way to use memcpy would be (from the description given)(a buffer I have at offset 32 into this new nodes array)

memcpy(nodes,buffer+32,sizeof(node)*nodecount);

or

memcpy(nodes,&buffer[0x20],sizeof(node)*nodecount);

Earlier you didn't pass the address, rather you passed the value itself. You made an attempt to access some memory location you are not supposed to leading to segmentation fault.

Upvotes: 5

Related Questions