yrmt yrmt - 1 month ago 20
C Question

C String concatenation using memcpy not appending

In some network code I need to encode packet structures in a buffer to send(2) over a socket but memcpy'ing the encoded buffers into a bigger buffer seems problematic.
Here's a small code example illustrating what I am doing:

char tbuf[] = "test";
char *buf = malloc(300);
memset(buf, '\0', 300);

int bytes_to_copy = 300;
int bytes_copied = 0;

while (bytes_copied < bytes_to_copy) {
memcpy(buf + bytes_copied, tbuf, sizeof(tbuf));
bytes_copied += sizeof(tbuf);
}
/* free, return */


This should append "test" 60 times into buf but buf ends up only containing one "test". Am I using memcpy wrong?

Answer

You are repeatedly copying the null terminator at the end of test. sizeof tbuf is 5.

So all the C standard library functions will ignore all the other concatenants.

The solution: copy one less byte in the memcpy, and be sure to add a null terminator to the final string.

Comments