MaMu
MaMu

Reputation: 1869

Memcpy copies more, than expected

I'm trying to copy x bytes. The size is counted and printed out(see below). I use memcpy to copy the counted amount of bytes. But as result I'm getting sometimes longer values. What is wrong?

This is a few of the code:

  size_t  symlen  = tmpP - cp;
  char * triP = malloc(symlen);
  printf("mallocated %zu\n", symlen) ;
  memcpy (triP, tmpP - (symlen) , symlen);
  printf(">>VAL %s<<\n", triP);

Here is some output and you can see, that value is longer as 15 characters.

mallocated 15
>>VAL 558657,1033,8144399,814<<
mallocated 15
>>VAL 558657,1033,8144399,814<<

Upvotes: 0

Views: 2660

Answers (2)

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

That's because you haven't added the null byte to the memcpy'd data. It looks like memcpy must've marked the page where it copied the string as copy-on-write, so when one accesses triP, one is actually accessing tmpP and thus the value of triP shown in the second printf is tmpP instead of gibberish data.

Upvotes: 2

Didier Trosset
Didier Trosset

Reputation: 37427

You should allocate one more byte, and write a null character in it to mark the end of the string.

size_t  symlen  = tmpP - cp;
char * triP = malloc(symlen+1);
printf("mallocated %zu\n", symlen) ;
memcpy (triP, tmpP - (symlen) , symlen);
tripP[symlen] = '\0';
printf(">>VAL %s<<\n", triP);

Upvotes: 5

Related Questions