> For the complete documentation index, see [llms.txt](https://www.ctfrecipes.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.ctfrecipes.com/pwn/stack-exploitation/stack-buffer-overflow/dangerous-functions/memcpy.md).

# memcpy

## Prototype

```c
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

```c
#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:

```c
#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.

1. Use the `memmove` function instead of `memcpy`. `memmove` is similar to `memcpy`, but it can handle overlapping memory regions, which makes it more suitable for cases where the source and destination buffers may overlap.
2. Use the `strlcpy` function, which is a variant of `strcpy` that includes a size parameter. `strlcpy` copies up to the specified size, and ensures that the destination string is null terminated.

For example:

```c
#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.
