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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?