How to prevent memcpy buffer overflow?

Michael D picture Michael D · Aug 31, 2012 · Viewed 33.9k times · Source

There are some binary buffer with fixed size in a program that are used to store data. And memcpy is used to copy the buffer from one to another one. Since the source buffer may be larger than the destination buffer. How can I detect if there is buffer overflow?

Answer

Jonathan Leffler picture Jonathan Leffler · Aug 31, 2012

You have to know how much data is in the source buffer and how much space is available in the target buffer.

Do not call memcpy() if there is not enough space in the target buffer for all the data you want to copy from the source buffer. (You have to decide whether it is OK to truncate the data if the source is bigger than the target.)

If you don't know, rewrite the code so that you do know how much space there is; otherwise, it is not safe.

Note that if there is a chance of the source and target buffers overlapping, you should use memmove() rather then memcpy().

In C++, look askance at using memcpy() in the first place; that is a C-style operation rather than C++.