Your memcpy() in the test() function is wrong.
int test(const char *buf) {
^^
a pointer !
memcpy(&b, &buf+1, 4);
memcpy(&d, &buf+5, 4);
You then take the address of the passed in pointer and add an offset to that, which wouldn't
point anywhere valid. So you invoke undefined behavior, if your program #1
happens to work, you
got lucky.
You must use:
memcpy(&b, buf+1, 4); memcpy(&d, buf+5, 4);
You have the same error in main()
. In main
you have char buf[100];
, which is an array, and not a pointer. Your pointer arithmetic (&buf + 5
) doesn't add 5 bytes to the start of buf
but it adds 5*sizeof buf
bytes to the pointer, and again you're copying bytes around to invalid space, outside your array.
The code in main() must be:
memcpy(buf+1, &a, 4);
memcpy(buf+5, &c, 4);
memcpy(&d, buf+5, 4);
memcpy(&b, buf+1, 4);