Memcpy - 为数据块分配值

时间:2013-11-07 03:33:21

标签: c memcpy

我有一大块内存,我将这些内存的一部分传递给这些函数:

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));
}

我的输出如下:

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

似乎设置了错误的值(我正在尝试设置指针和整数。这对memcpy来说是不正确的用法?

1 个答案:

答案 0 :(得分:3)

在第一个函数中,当您输出刚写入的值时,不会取消引用指针。试试这个:

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

第二个功能中存在同样的问题。您希望输出存储在指针node+4内的指针值,而不是node+4本身:

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

关于memcpy,使用它来编写单个值很奇怪。您可以避免memcpy这样:

*(int*)node = size;
*(char**)(node+4) = next;