memcpy
Prototype
void* memcpy(void* dest, const void* src, size_t n);
This function copies n
bytes from the memory location pointed to by src
to the memory location pointed to by dest
. The dest
and src
arrays must not overlap, and the dest
array must be large enough to hold n
bytes.
Vulnerable example
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer[8];
memcpy(buffer, argv[1], strlen(argv[1]));
return 0;
}
In this code, the memcpy
function is used to copy the contents of argv[1]
(a command line argument) into the buffer
array, which has a fixed size of 8 bytes. If the length of argv[1]
is greater than 8 bytes, it will overwrite memory beyond the bounds of the buffer
array, potentially causing a buffer overflow.
Prevent
Use the strnlen
function to determine the length of the source string, and pass this value as the size parameter to memcpy
. For example:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer[8];
size_t len = strnlen(argv[1], sizeof(buffer));
memcpy(buffer, argv[1], len);
return 0;
}
This will ensure that the memcpy
function only copies up to the maximum size of the buffer, preventing a buffer overflow.
Use the
memmove
function instead ofmemcpy
.memmove
is similar tomemcpy
, but it can handle overlapping memory regions, which makes it more suitable for cases where the source and destination buffers may overlap.Use the
strlcpy
function, which is a variant ofstrcpy
that includes a size parameter.strlcpy
copies up to the specified size, and ensures that the destination string is null terminated.
For example:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer[8];
strlcpy(buffer, argv[1], sizeof(buffer));
return 0;
}
Using any of these methods can help prevent buffer overflow vulnerabilities when using the memcpy
function.
Last updated