Reputation: 907
I am wondering if I am using the memcpy function right.
So I have a two-dim. array of strings, and when I try to fill them valgrind tells me
==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
}
When I change it to: &test[i][0]
then the strings in test stay empty :S.. I also tried to remove the & of to_fill but with this my program just crashes.. I have no Idea what I am doing wrong here.
I changed all of the suggestions but the same error of valgrind appears, I even tried to put a constant char array into to_fill but still:
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';
}
Upvotes: 0
Views: 1550
Reputation: 3698
Your memcpy statement is wrong, you don't need to dereference a char pointer which holds the address as it's value. Do this instead:
memcpy(test[i], to_fill, strlen(to_fill));
When you do:
memcpy(test[i], &to_fill, strlen(to_fill));
the memory address where to_fill
is stored is passed to the function.
What you want to pass is the memory to which to_fill
, the pointer, points to.
Upvotes: 1