memcpy在二维数组上

时间:2014-09-27 14:32:14

标签: c

我想知道我是否正在使用memcpy函数。

所以我有两个昏暗。字符串数组,当我尝试填充它们时,valgrind告诉我

==825== Invalid write of size 8
==825==    at 0x344B8E: _platform_memmove$VARIANT$Unknown (in            /usr/lib/system/libsystem_platform.dylib)
==825==    by 0x1C4D74: __memcpy_chk (in /usr/lib/system/libsystem_c.dylib)
==825==    by 0x100001328: generate_test_data (check_generate_test_data.c:4120)
==825==    by 0x100000CA6: main (check_generate_test_data.c:137)
==825==  Address 0x100030a00 is 0 bytes after a block of size 32 alloc'd
==825==    at 0x47F1: malloc (vg_replace_malloc.c:302)
==825==    by 0x100000FBB: generate_test_data (check_generate_test_data.c:4095)
==825==    by 0x100000CA6: main (check_generate_test_data.c:137)


 int i;
 char **test;
 int total = 4;
 int elements = 11;
 test = malloc(sizeof(char**)* total);
 for (i=0; i < total; i++) {
    // char *to_fill --//is filled with a method
    //  
    test[i] = malloc(sizeof(char*) * elements;    // <== here is where compiler complains
    memcpy(&test[i], &to_fill, strlen(to_fill);   // <== here is where valgrind complains
 }

当我将其更改为:       &安培;试验[Ⅰ] [0]

然后测试中的字符串保持空白:S ..我也试图删除&amp; to_fill但是这个我的程序崩溃了......我不知道我在这里做错了什么。


我改变了所有的建议但是出现了同样的valgrind错误,我甚至尝试将一个常量的char数组放入to_fill但仍然:

 int i;
 char **test;
 char *to_fill;
 int total = 4;
 int elements = 11;
 test = malloc(sizeof(char*)* total);
 to_fill = malloc(sizeof(char)* 100);
 to_fill[0] = '\0';
 for (i=0; i < total; i++) {
   //to_fill = method_to_fill_it(); 
   strncpy(to_fill, "example", 7);
   to_fill[7] = '\0';
   test[i] = malloc(sizeof(char*) * elements;
   memcpy(&test[i], &to_fill, strlen(to_fill);   // <== here is where valgrind complains
   to_fill[0] = '\0';
 }

1 个答案:

答案 0 :(得分:1)

你的memcpy声明是错误的,你不需要取消引用一个字符指针,它保存地址作为它的值。这样做:

 memcpy(test[i], to_fill, strlen(to_fill)); 

当你这样做时:

 memcpy(test[i], &to_fill, strlen(to_fill)); 

将存储to_fill的内存地址传递给函数。

您要传递的是指针指向to_fill的内存。