-1

Possible Duplicate:
Problem when copying memory

(tuple1 and tuple2 are void pointers passed to this function)

char *data;

data = (char*) calloc (84, 1);

memcpy(data, tuple1, 44);

memcpy(data+44, tuple2, 40);

I have allocated 84 bytes for data. I am doing the first memory copy memcpy(data, tuple1, 44); which copies 44 bytes from the address of tuple1 to the address of data and when I try to read data it turns out that it had copied the bytes of tuple1 on the first 44 bytes of data and then it had copied again the 44 bytes of tuple1 until it has filled the 84 bytes allocated for data.

When I do the second memory copy I try to paste the 40 bytes of tuple2 44 bytes after the address of data. In reality it does the same thing as with tuple1 and even more - it starts pasting from the address of data and not 44 bytes after the address of data.

Why is that?! And how can I prevent it? Anyone help, I'm very desperate.

Community
  • 1
  • 1
Ivan Kolev
  • 1
  • 1
  • 1

3 Answers3

0

What are the definitions of tuple1 and tuple2? Are they at least of size 44 and 40 (respectively)? Do they perhaps point into the same memory as data?

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
0

If you are treating the data as a string, you may be missing a null terminator.

You have used calloc to initialize the memory to zero but if you have overwritten every single byte there is nothing left to terminate the string.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
-1

you should use addresses.

memcpy(&data, &tuple1, 44);

memcpy(&data+44, &tuple2, 40);

may help.

mo.
  • 3,474
  • 1
  • 23
  • 20
  • 1
    Um, no. Firstly this looks like guesswork. Secondly it's dangerous to guess like this. Thirdly, `data`, `tuple1` and `tuple2` are already pointers. Your code is trying to write _into those pointers and beyond_. Yikes! – Lightness Races in Orbit Apr 05 '11 at 22:09
  • uh, i just read the last two lines and didnt see the *. tomalak is right. – mo. Apr 05 '11 at 22:13