Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcpy - assigning values to block of data

Tags:

c

memcpy

I have a large block of memory and I am passing bits of this memory to these functions:

void setBlockSize(char* node, int size) {
    printf("need size: %i\n",size);
    memcpy(node, (void *)&size, sizeof(size));
    printf("set to: %i\n",node); 
}

//written for 4 byte pointer, 32 bit addressing
void setNextPointer(char* node, char* next){
    printf("need ptr: %p\n", next);
    memcpy((node+4), (void*)&next, sizeof(next));
    printf("next: %p, set: %p\n",next, (void*)(node+4));
}

My output is as follows:

need size: 8296
set to: 137666560
need ptr: (nil)
next: (nil), set: 0x834a004
need size: 137666456
set to: 137666560
need ptr: 0xffee4874
next: 0xffee4874, set: 0x834a004
need size: 104
zsh: segmentation fault (core dumped)  ./mallocTest

It appears that the wrong values are being set (I am trying to set a pointer, and an integer. Is this not correct usage for memcpy?

like image 743
Algonomaly Avatar asked Jan 17 '26 00:01

Algonomaly


1 Answers

In the first function, you are not dereferencing the pointer when you output the value you just wrote to. Try this:

printf("set to: %i\n", *(int*)node); 

Same problem is present in the second function. You want to output the pointer value stored inside the pointer node+4, not node+4 itself:

printf("next: %p, set: %p\n", next, *(void*)(node+4));

Just regarding memcpy, it's strange to use it for writing a single value. You can avoid memcpy like this:

*(int*)node = size;
*(char**)(node+4) = next;
like image 118
paddy Avatar answered Jan 19 '26 16:01

paddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!