# sprintf

## Prototype

```c
int sprintf(char* str, const char* format, ...);
```

This function writes a formatted string to the array pointed to by `str`. The `format` argument is a string that specifies how the subsequent arguments are formatted. The `...` indicates that the function can take a variable number of arguments.

## Vulnerable example

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

int main(int argc, char *argv[]) {
  char buffer[8];
  sprintf(buffer, "%s", argv[1]);
  return 0;
}
```

{% hint style="info" %}
In this code, the `sprintf` 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.
{% endhint %}

## Prevent

To prevent this vulnerability, the program should ensure that the length of the data being written to the buffer is within the bounds of the buffer's size. For example, the following code uses `snprintf` (a variant of `sprintf` that includes a size parameter) to ensure that the data being written to the buffer does not exceed its size:

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

int main(int argc, char *argv[]) {
  char buffer[8];
  snprintf(buffer, sizeof(buffer), "%s", argv[1]);
  return 0;
}
```

{% hint style="info" %}
Using `snprintf` ensures that the data written to the `buffer` array does not exceed its size, and prevents a buffer overflow vulnerability.&#x20;
{% endhint %}


---

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