我在想我是否正在使用memcpy函數。二維數組上的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
}
當我將其更改爲: &測試[I] [0]
然後測試該字符串留空:S。 。我也嘗試刪除to_fill的&,但是這個程序只是崩潰..我不知道我在這裏做錯了什麼。
我改變了所有的建議,但出現的valgrind的同樣的錯誤,我甚至試圖把一個恆定的字符數組到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';
}
您正在計算基於*指針*的大小的malloc參數,而不是*指向*的類型。 – 2014-09-27 14:34:25
另請注意,字符串的大小是(length + 1)* sizeof(element)。 – Deduplicator 2014-09-27 14:35:19
你的意思是第一個malloc?但我怎麼能做到這一點,我想我首先必須說我將有多少字符數組,所以第一維(4),然後爲每個數組,有多少元素 - 它會得到 – malajedala 2014-09-27 14:36:16