简体   繁体   English

如何正确使用memcpy?

[英]How to properly use memcpy?

I have a mainbuf[bufsize] , empty initially. 我有一个mainbuf[bufsize] ,最初是空的。

I am reading from some input : read(fd, otherbuf, sizeof(otherbuf)) different strings which are assigned to otherbuf . 我正在读取一些输入: read(fd, otherbuf, sizeof(otherbuf))分配给otherbuf不同字符串。 Every time I assign a new string to otherbuf I want to append it to mainbuf . 每次我给otherbuf分配一个新字符串时,我想将它附加到mainbuf

I do: 我做:

memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff) but it does not give me all the strings. memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff)但它没有给我所有的字符串。 Usually the last otherbuf is right, but all the other ones are missing characters. 通常最后一个otherbuf是正确的,但所有其他的都缺少字符。

You need to change the destination pointer each time you call memcpy . 每次调用memcpy时都需要更改目标指针。

For example, suppose you have 4 bytes in mainbuf now. 例如,假设您现在在mainbuf有4个字节。 Next you receive 10 bytes. 接下来你会收到10个字节。 Here is how to append it: 以下是如何追加它:

memcpy(mainbuf + 4, otherbuf, 10);

memcpy replaces memory, it does not append. memcpy替换内存,它不会追加。 If you want to use memcpy, your code will need to be a little more complex. 如果你想使用memcpy,你的代码需要更复杂一些。

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

When you pass in mainbuf, you are passing the same destination address each time. 传入mainbuf时,每次都传递相同的目标地址。 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. 每次使用memcpy时都需要递增目标地址,以便将其放在后续内存中,而不是每次都覆盖相同的字符串。

Try using strcat instead, it is designed to concatenate strings together, which sounds like what you want to do. 尝试使用strcat,它旨在将字符串连接在一起,这听起来像你想要做的。 Make sure you check you have enough memory left before you use it, so you don't encounter memory issues. 在使用之前,请确保检查是否有足够的内存,因此不会遇到内存问题。

The description of the problem sounds like the appropriate use of strcat . 问题的描述听起来像是strcat的恰当使用。 Strcat must be handled with care since it can easily write beyond the bounds of a buffer. 必须小心处理Strcat,因为它可以轻松地写入超出缓冲区的范围。 For that reason, here are variations like strncat() which can prevent buffer overruns—if used correctly. 出于这个原因,这里有像strncat()这样的变体,可以防止缓冲区溢出 - 如果使用正确的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM