October 23, 2024
Chicago 12, Melborne City, USA
C#

Practice to use memcpy or strncpy to copies the string into memory


I am writing a piece of simple practice to compare the usage of between memcpy or strncpy. I see that I can do this string copy using either of these two functions:

char * strncpy ( char * destination, const char * source, size_t num );

and

void * memcpy ( void * destination, const void * source, size_t num );

Simple practice

    char src[] = "Hello World";
    char dst[20];

    strncpy(dst, src, 5);
    printf("%zu-", strlen(dst));

    memcpy(dst, src, sizeof(dst));
    printf("%zu-", strlen(dst));

    strncpy(dst, src, 5);
    printf("%zu", strlen(dst));

The actually output

5-11-11

How can I understand what the behave differently with respect?

In general, how can I find out relative bytes of memory block different copied by using memcpy or strncpy?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video