Search code examples
cmemcpy

Memcpy - assigning values to block of data


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?


Solution

  • 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;