There are some binary buffers with fixed sizes 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?
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++.