What is the difference between memcpy and snprintf

Asked

Viewed 136 times

2

I see people using snprintf when I would use memcpy. I even did some tests and it worked with memcpy. Now I was in doubt of why to use one and not the other. And what the real meaning of the two.

  • Could you put an example, a context? Really can use in certain cases, the ideal is to use within the intended semantics, when both serve equal.

2 answers

3

Both functions have very distinct purposes and are not equivalent. One is not able to replace the other without an additional implementation.

The purpose of the function snprintf() is to format strings terminated at zero.

The purpose of the function memcpy() is to copy the contents from one given memory position to another.

If you use memcpy() to manipulate strings, you will need to ensure that the terminator \0 or NULL is present at the end of the string because memcpy() does not guarantee that.

The function memcpy() is rather primitive, while snprintf() has a more elaborate implementation, able to interpret the directives of string de formatação enabling conversion of types, numerical bases, etc.

I’ve seen scenarios (horrible) where the function snprintf() was used to copy strings:

snprintf( dst, strlen(orig), orig );   /* Não faça isso! */

All this pussycat can be replaced by only:

strcpy( dest, orig );

Which, oddly enough, is equivalent to:

memcpy( dest, orig, strlen(orig) + 1 ); /* Não, não, não! */

Are you not in some kind of horrible scenario out there ?

  • 1

    best use strncpy than teaching the class to write insecure code with strcpy just because "it’s easier to learn like this".

2

They’re not the same.

The memcpy function copies n bytes from the memory position pointed by the first parameter to the positions from the address of the second parameter.

The snprintf function writes from the specified memory position by performing the formatting defined in the parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.