# strcat

## Prototype

```c
char* strcat(char* dest, const char* src);
```

This function appends a copy of the string pointed to by `src` (including the terminating null character) to the end of the string pointed to by `dest`. The `dest` array must be large enough to hold the combined strings, including the terminating null character.

## Vulnerable example

```c
#include <stdio.h>
#include <string.h>

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

  // The strcat function concatenates the second string to the end of the first
  // string. It does not check for buffer overflows, so if the first string is
  // not large enough to hold the second string, it will write beyond the bounds
  // of the buffer, potentially leading to a buffer overflow vulnerability.

  strcat(buffer, argv[2]);
  
  printf("%s\n", buffer);
  return 0;
}
```

## Prevent

To prevent this vulnerability, use the `strlcat` function instead of `strcat` to concatenate the second string to the end of the `buffer` string.&#x20;

The `strlcat` function allows to specify the maximum number of characters to be copied from the source string and ensure that the destination string is always null-terminated , which can help to prevent the destination buffer from being overrun with data.

```c
#include <stdio.h>
#include <string.h>

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

  strlcat(buffer, argv[2], sizeof(buffer) - strlen(buffer) - 1);

  printf("%s\n", buffer);
  return 0;
}
```

{% hint style="info" %}
In this example, the `strlcat` function is used to concatenate the second string stored in `argv[2]` to the end of the `buffer` string. The third argument to `strlcat` specifies the maximum number of characters to be copied from the source string. This value is calculated by subtracting the length of the `buffer` string from the size of the `buffer` array and then subtracting 1 to leave room for the null-terminator.
{% endhint %}

## &#x20;


---

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