> 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/strcat.md).

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