# strcpy

## Prototype&#x20;

```c
char * strcpy(char * dest, const char * src)
```

This function copies the string pointed to by `src` (including the terminating null character) to the array pointed to by `dest`. The `dest` array must be large enough to hold the entire string, including the terminating null character.

## Vulnerable example

```c
#include <string.h>

int main(int argc, char* argv[])
{
    char buffer[10];
    strcpy(buffer, argv[1]);
    return 0;
}
```

{% hint style="info" %}
In this example, the `buffer` array is defined with a size of 10 bytes, but the `strcpy` function is used to copy the first command-line argument (which is passed to the program as `argv[1]`) into the buffer without checking the length of the argument. If the first command-line argument is longer than 10 bytes, `strcpy` will write beyond the bounds of the `buffer` array, potentially causing a buffer overflow.
{% endhint %}

## Prevent

To prevent this vulnerability  use the `strlcpy` function instead of `strcpy`. `strlcpy` is similar to `strcpy`, but it takes an additional argument that specifies the maximum number of characters to copy and ensure that the destination string is always null-terminated. This ensure that `strlcpy` does not write beyond the bounds of the destination buffer.

```c
#include <string.h>

int main(int argc, char* argv[])
{
    char buffer[10];
    strlcpy(buffer, argv[1], sizeof(buffer));
    return 0;
}
```

{% hint style="info" %}
In this example, the `strlcpy` function copies at most `sizeof(buffer) - 1` characters from `argv[1]` to `buffer.`
{% endhint %}

It is also a good idea to check the length of `argv[1]` before calling `strlcpy`, to ensure that it is not longer than `sizeof(buffer) - 1` characters. This can help to prevent a buffer overflow if the user passes a very long command-line argument to the program.

```c
#include <string.h>

int main(int argc, char* argv[])
{
    char buffer[10];
    if (strlen(argv[1]) >= sizeof(buffer))
    {
        // Handle error - argv[1] is too long
    }
    else
    {
        strlcpy(buffer, argv[1], sizeof(buffer));
    }
    return 0;
}
```


---

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