user461316
user461316

Reputation: 913

How to properly use memcpy?

I have a mainbuf[bufsize], empty initially.

I am reading from some input : read(fd, otherbuf, sizeof(otherbuf)) different strings which are assigned to otherbuf. Every time I assign a new string to otherbuf I want to append it to mainbuf.

I do:

memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff) but it does not give me all the strings. Usually the last otherbuf is right, but all the other ones are missing characters.

Upvotes: 13

Views: 48679

Answers (3)

wallyk
wallyk

Reputation: 57794

The description of the problem sounds like the appropriate use of strcat. Strcat must be handled with care since it can easily write beyond the bounds of a buffer. For that reason, here are variations like strncat() which can prevent buffer overruns—if used correctly.

Upvotes: 1

mikehabibi
mikehabibi

Reputation: 137

memcpy replaces memory, it does not append. If you want to use memcpy, your code will need to be a little more complex.

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

When you pass in mainbuf, you are passing the same destination address each time. You need to increment the destination address everytime you use memcpy so that it places it in subsequent memory, instead of overwriting the same string each time.

Try using strcat instead, it is designed to concatenate strings together, which sounds like what you want to do. Make sure you check you have enough memory left before you use it, so you don't encounter memory issues.

Upvotes: 4

Donotalo
Donotalo

Reputation: 13035

You need to change the destination pointer each time you call memcpy.

For example, suppose you have 4 bytes in mainbuf now. Next you receive 10 bytes. Here is how to append it:

memcpy(mainbuf + 4, otherbuf, 10);

Upvotes: 21

Related Questions