How do I validate lengths before memcpy/memmove in C++?

In C++, when using functions like memcpy or memmove, it's crucial to validate the lengths of the memory blocks being copied or moved. Not validating these lengths can lead to buffer overflows, memory corruption, or crashes. Below is a simple example demonstrating how to perform length validation before using these functions.

#include #include void safeMemcpy(char* dest, const char* src, size_t destSize, size_t srcSize) { if (destSize < srcSize) { std::cerr << "Error: Destination buffer is smaller than source buffer!" << std::endl; return; } memcpy(dest, src, srcSize); } int main() { const char* source = "Hello, World!"; const size_t sourceSize = strlen(source) + 1; // +1 for null terminator char destination[20]; safeMemcpy(destination, source, sizeof(destination), sourceSize); std::cout << "Copied string: " << destination << std::endl; return 0; }

C++ memory management memcpy memmove buffer overflow safe coding