3

I am trying to copy the first 16 bytes of a 32 byte string to dest.

unsigned char src[32] = "HELLO-HELLO-HELLO-HELLO-HELLO-12";
unsigned char dest[16];

memcpy(dest, src, 16); // COPY

printf("%s\n", src);
printf("%lu\n", strlen(src));

printf("%s\n", dest);
printf("%lu\n", strlen(dest));

The output is the following

HELLO-HELLO-HELLO-HELLO-HELLO-12
32
HELLO-HELLO-HELLHELLO-HELLO-HELLO-HELLO-HELLO-12
48

I was expecting to receive HELLO-HELLO-HELL in dest only. The first 16 bytes of dest actually contain the expected result.

Why does dest more than it can actually hold? Why does it have a length of 16+32=48? Is there a way to copy only the first 16 bytes of src to dest?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
desktop
  • 145
  • 2
  • 7
  • 2
    If you want to copy a 16 character string, you need a 17 character buffer, and ensure that the last character is a `\0`. What's happening here is a classic printing from an unterminated string yielding garbage (which in this case is the remaining characters from the src string). – Anya Shenanigans Dec 10 '14 at 21:00
  • Take a look at the [string tag-wiki](https://stackoverflow.com/tags/string/info). – Deduplicator Dec 10 '14 at 21:01
  • Use strcpy or strncpy instead of memcpy and read up about how C strings which are not really strings like those in other languages but null terminated array's of char. – hookenz Dec 10 '14 at 21:05
  • Also, the string you assign to src is 33 characters long. – Lee Daniel Crocker Dec 10 '14 at 21:08

2 Answers2

7

The 16 bytes allocated for dest need to include a byte for the trailing NULL ('\0') -- since you wrote 16 bytes, you have a non-null terminated string.

Since the computer you are on has the stack organized in a particular way, you are proceeding past the end of dest and then printing src.

So, to copy 16 bytes, allocate 17 to leave room for the trailing null, and initialize it.

unsigned char dest[17]={0};

Alternative, after copying it, null terminate it:

memcpy(dest, src, 16); // COPY
dest[16]='\0';
JohnH
  • 2,713
  • 12
  • 21
3

You're not accounting for the fact that strings are null terminated. There is a '\0'character at the end of the "HELLO..." string constant. Take a look at

http://www.tutorialspoint.com/c_standard_library/c_function_strncpy.htm

That should point you in the right direction. memcpy doesn't provide help for C Strings - just raw memory.

KirkSpaziani
  • 1,962
  • 12
  • 14