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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ctfrecipes.com/pwn/stack-exploitation/stack-buffer-overflow/dangerous-functions/memcpy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
