问题
So there is a problem I am headbanging over two nights in a row:
(tuple1 and tuple2 are void pointers passed to this function)
char *data;
data = (char*) calloc (76, 1);
memcpy(data, tuple1, 32);
memcpy(data+32, tuple2, 44);
The idea is to allocate memory equal to the sum of the sizes of tuple1 and tuple2 (tuple1 is 32 bytes and tuple2 is 44) and then copy the 32 bytes of tuple1 and paste them at the address of data and after that copy the 44 bytes of tuple2 and paste them 32 bytes after the address of data.
The thing is if I copy only tuple1 or only tuple2 it is really copied where it is supposed to be (I am printing data with way too long function to put here), but when I do the two memory copies the first memcpy() works fine but the second doesn't.
Can anyone help me with this serious problem?
回答1:
I would suspect issues with alignment and/or padding, what are the type declarations of tuple1 and tuple2?
How do you know their exact sizes? Code that hardcodes things is suspect, there should be some use of sizeof rather than magic number literals.
Also, you shouldn't cast the return value of calloc(), in C.
回答2:
Begin your experiment with something smaller, which is easier to debug:
void* tuple1 = calloc(2, 1);
char* content1 = "ab";
memcpy(tuple1, content1, 2);
void* tuple2 = calloc(4, 1);
char* content2 = "cdef";;
memcpy(tuple2, content2, 4);
char *data = data = (char*) calloc (6, 1);
memcpy(data, tuple1, 2);
memcpy(data+2, tuple2, 4);
printf("%.*s\n", 6, data); // should print: abcdef
来源:https://stackoverflow.com/questions/5554730/problem-when-copying-memory