How to use memcpy?

I have mainbuf[bufsize] empty initially.

I am reading from some input: read(fd, otherbuf, sizeof(otherbuf)) different lines that are assigned to otherbuf . Each time I assign a newline to otherbuf , I want to add it to mainbuf .

I do:

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

+6
source share
3 answers

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

For example, suppose you now have 4 bytes in mainbuf . Then you get 10 bytes. Here's how to add it:

 memcpy(mainbuf + 4, otherbuf, 10); 
+18
source

memcpy replaces memory; it is not added. If you want to use memcpy, your code should be a little more complicated.

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

When you go to mainbuf, you pass the same destination address every time. You need to increment the destination address every time you use memcpy so that it puts it in the next memory, instead of rewriting the same line every time.

Try strcat instead, it is designed to concatenate strings together, which is similar to what you want to do. Make sure you check that you have enough memory left before using it so that there are no memory problems.

+3
source

The description of the problem sounds like the appropriate use of strcat . Strcat should be handled with care, as it can easily write outside the buffer. For this reason, options such as strncat() are presented here that can prevent buffer overflows - if used correctly.

+1
source

Source: https://habr.com/ru/post/885452/


All Articles