How to properly use memcpy?

44,916

Solution 1

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);

Solution 2

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.

Solution 3

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.

Share:
44,916

Related videos on Youtube

user461316
Author by

user461316

Updated on July 09, 2022

Comments

  • user461316
    user461316 almost 2 years

    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.

Related