In general, any function that does not check bounds in the arguments. A list would be

  • gets()
  • scanf()
  • strcpy()
  • strcat()

You should use size limited versions like stncpy, strncat, fgets, etc. Then be careful while giving the size limit; take into consideration the '\0' terminating the string.

Also, arrays are NOT bound checked in C or C++. The following example would cause errors. See off by one error

int foo[3];
foo[3] = WALKED_OFF_END_OF_ARRAY;

edit: Copied answers of @MrValdez , @Denton Gentry

Answer from hayalci on Stack Overflow
🌐
OWASP Foundation
owasp.org › www-community › vulnerabilities › Buffer_Overflow
Buffer Overflow | OWASP Foundation
At the code level, buffer overflow vulnerabilities usually involve the violation of a programmer’s assumptions. Many memory manipulation functions in C and C++ do not perform bounds checking and can easily overwrite the allocated bounds of the buffers they operate upon.
🌐
Jmu
users.cs.jmu.edu › bernstdh › web › common › lectures › summary_vulnerabilities_c_buffer-overflows.php
Buffer Overflows in C - Computer Science - JMU
An Example · char a[10], b[10]; strncpy(a, "0123456789", 10); // a will not be null-terminated strcpy(b, a); // b will probably overflow · Threats - Memory Corruption · The Issue: By overflowing a buffer the attacker can corrupt memory that is being used to store information of various kinds ·
Discussions

Buffer Overflow Vulnerability C Code
I'm assuming this is a copy paste of your homework, so, did you try to do it and have an specific question? Are your stuck somewhere? More on reddit.com
🌐 r/C_Programming
6
0
February 28, 2023
What C/C++ functions are most often used incorrectly and can lead to buffer overflows? - Stack Overflow
I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't e... More on stackoverflow.com
🌐 stackoverflow.com
How is printf() in C/C++ a Buffer overflow vulnerability? - Information Security Stack Exchange
Stack Exchange network consists ... Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. Visit Stack Exchange ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... According to an article I just read, the functions printf and strcpy are considered security vulnerabilities due to Buffer ... More on security.stackexchange.com
🌐 security.stackexchange.com
October 9, 2013
c - Why is this code vulnerable to buffer overflow attacks? - Stack Overflow
Outside of the scope of the function, we don't care. 2015-04-28T06:20:37.05Z+00:00 ... " the buffer in which str is stored" -- that's not a buffer overflow, which is the issue here. And every answer has that "problem", which is unavoidable given the signature of func ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Acunetix
acunetix.com › home › web security blog › what is a buffer overflow
What Is a Buffer Overflow | Acunetix
January 14, 2025 - That is why the safest basic method in C is to avoid the following five unsafe functions that can lead to a buffer overflow vulnerability: printf, sprintf, strcat, strcpy, and gets.
🌐
Reddit
reddit.com › r/c_programming › buffer overflow vulnerability c code
r/C_Programming on Reddit: Buffer Overflow Vulnerability C Code
February 28, 2023 -

Hi folks,

I have this c code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int ssp(char * str)
{
    char buffer[100];
    strcpy(buffer,str);

    return 1;
}

int main(int argc, char **argv)
{
    char str[400];
    FILE * afile;

    afile = fopen("afile", "r");
           fread(str, sizeof(char), 400, afile);
    ssp(str);

    printf("Returned Properly\n");  

    return 1;
}

The program provided reads the contents of a file called `"afile"` into a character array called `str`, which can hold up to 400 characters. It then calls the `ssp` function and passes `str` as an argument.

The `ssp` function copies the contents of the `str` character array into a local character array called buffer. The `strcpy` function used to copy the string data does not perform any bounds checking, which can lead to buffer overflow vulnerabilities if the input string is longer than the buffer size.

However, the lack of bounds checking in the `strcpy` function in the `ssp` function can potentially lead to buffer overflow vulnerabilities if used in a larger program or in an environment with untrusted input data.

Could anyone please assist with a shellcode at the end of "afile" and then store the shellcode on the stack to run? Please...

🌐
OWASP Foundation
owasp.org › www-community › attacks › Buffer_overflow_attack
Buffer Overflow Attack | OWASP Foundation
The following question arises: The buffer stores only eight characters, so why did function printf() display twelve?. The answer comes from the process memory organisation. Four characters which overflowed the buffer also overwrite the value stored in one of the registers, which was necessary for the correct function return.
🌐
Medium
infosecwriteups.com › exploiting-stack-buffer-overflows-over-functions-670765bf405a
EXPLOITING STACK BUFFER OVERFLOWS OVER FUNCTIONS
May 16, 2021 - In this program we can see a function named “hidden” which is not being called in “main()” · So the actual program should receive input and print it as output · It should not display the contents inside the “hidden()” ... To test stack based buffer overflows in Linux, you need to compile the source code with certain flags to enable “DISABLE STACK PROTECTION & STACK EXECUTION”
Find elsewhere
🌐
Tenouk
tenouk.com › Bufferoverflowc › Bufferoverflow1.html
An introduction to computer buffer overflow problem on using unsecured C or C++ standard functions in C programs
A buffer overflow that injects ... exploitable buffer overflow. A certain class of well documented strings and characters manipulation functions that may be used together with an array variables for their arguments or inputs, such as ... , is naturally vulnerable to buffer ...
🌐
Wikipedia
en.wikipedia.org › wiki › Buffer_overflow
Buffer overflow - Wikipedia
February 9, 2026 - When available, the strlcpy library function is preferred over strncpy which does not null-terminate the destination buffer if the source string's length is greater than or equal to the size of the buffer (the third argument passed to the function). Therefore a may not be null-terminated and cannot be treated as a valid C-style string. The techniques to exploit a buffer overflow vulnerability vary by architecture, operating system, and memory region.
🌐
Ucdavis
spc.cs.ucdavis.edu › index.php › situations › buffer-overflow
Buffer Overflow
Here are some examples of buffer overflow vulnerability and ways to handle them. Storing data into a buffer without performing bounds checking. ... Pointer accessing heap memory. Using gets( ) causes buffer overflow. Use fgets( ) instead. Print or copy a string with a printf( ) function (Format String Vulnerabilities).
🌐
Invicti
invicti.com › learn › buffer-overflow-stack-overflow-heap-overflow
Buffer Overflow
The strcpy function in the above example copies the command argument into the destination buffer variable without checking the argument string length. The program only allocates 10 bytes to the buffer string, so this strcpy call results in a buffer overflow vulnerability.
🌐
Tenouk
tenouk.com › Bufferoverflowc › Bufferoverflow4.html
A step-by-step on the computer buffer overflow vulnerability tutorials on Intel x86 processor and C standard function call
Previously, before any buffer overflow protection implemented, these functions are already loaded into memory of the system atfixed addresses. This type of attack does not depend on executing code on the stack area but does depend on executing the existing and legitimate codes. This exploit normally combined with other type of vulnerabilities such as format strings and Unicode which act as malicious inputs.
🌐
Medium
int0x33.medium.com › day-49-common-c-code-vulnerabilities-and-mitigations-7eded437ca4a
Day 49: Common C Code Vulnerabilities and Mitigations | by int0x33 | Medium
February 17, 2019 - Uncontrolled format string is a vulnerability category which can cause information leakage and overwriting of memory. The following functions are also vulnerable: printf, fprintf, sprintf and snprintf.
🌐
Code Intelligence
code-intelligence.com › blog › buffer-overflows-complete-guide
Everything about Buffer Overflows | Blog | Code Intelligence
Learn how to detect, prevent, and fix buffer overflows, one of the most dangerous vulnerabilities in C/C++ software security. Read all about here!
🌐
Dhavalkapil
dhavalkapil.com › blogs › Buffer-Overflow-Exploit
Buffer Overflow Exploit - Dhaval Kapil
April 3, 2015 - You have entered in the secret function! Illegal instruction (core dumped) Cool! we were able to overflow the buffer and modify the return address. The secretFunction got called. But this did foul up the stack as the program expected secretFunction to be present. ... Whenever you are using buffers, be careful about their maximum length. Handle them appropriately. While managing BackdoorCTF I devised a simple challenge based on this vulnerability.
🌐
Fortinet
fortinet.com › resources › cyberglossary › buffer-overflow
What Is Buffer Overflow? Attacks, Types & Vulnerabilities | Fortinet
The system cannot limit the data that is read by the function, which makes code safety reliant on users entering fewer than ‘BUFSIZE’ characters. This code could look like this: ... Other buffer overflow attacks rely on user input to control behavior then add indirection through the memory function ‘memcpy()’. This accepts the destination buffer, source buffer, and amount of bytes to copy, fills the input buffer with the ‘read()’ command, and specifies how many bites for ‘memcpy()’ to copy.
🌐
GitHub
github.com › muhammet-mucahit › Security-Exercises
GitHub - muhammet-mucahit/Security-Exercises: :heavy_exclamation_mark: Buffer Overflow Exploitation Examples · GitHub
As you understand it from the project title, we are going to examine the gets function that is the one of vulnerable functions of C, in this project. It completely depends on the imagination of the attacker.
Starred by 48 users
Forked by 15 users
Languages   Python 52.1% | C 41.3% | Assembly 6.6%
Top answer
1 of 5
197

On most compilers the maximum value of an unsigned short is 65535.

Any value above that gets wrapped around, so 65536 becomes 0, and 65600 becomes 65.

This means that long strings of the right length (e.g. 65600) will pass the check, and overflow the buffer.


Use size_t to store the result of strlen(), not unsigned short, and compare len to an expression that directly encodes the size of buffer. So for example:

char buffer[100];
size_t len = strlen(str);
if (len >= sizeof(buffer) / sizeof(buffer[0]))  return -1;
memcpy(buffer, str, len + 1);
2 of 5
28

The problem is here:

strncpy(buffer,str,strlen(str));
                   ^^^^^^^^^^^

If the string is greater than the length of the target buffer, strncpy will still copy it over. You are basing the number of characters of the string as the number to copy instead of the size of the buffer. The correct way to do this is as follows:

strncpy(buffer,str, sizeof(buff) - 1);
buffer[sizeof(buff) - 1] = '\0';

What this does is limit the amount of data copied to the actual size of the buffer minus one for the null terminating character. Then we set the last byte in the buffer to the null character as an added safeguard. The reason for this is because strncpy will copy upto n bytes, including the terminating null, if strlen(str) < len - 1. If not, then the null is not copied and you have a crash scenario because now your buffer has a unterminated string.

Hope this helps.

EDIT: Upon further examination and input from others, a possible coding for the function follows:

int func (char *str)
  {
    char buffer[100];
    unsigned short size = sizeof(buffer);
    unsigned short len = strlen(str);

    if (len > size - 1) return(-1);
    memcpy(buffer, str, len + 1);
    buffer[size - 1] = '\0';
    return(0);
  }

Since we already know the length of the string, we can use memcpy to copy the string from the location that is referenced by str into the buffer. Note that per the manual page for strlen(3) (on a FreeBSD 9.3 system), the following is stated:

 The strlen() function returns the number of characters that precede the
 terminating NUL character.  The strnlen() function returns either the
 same result as strlen() or maxlen, whichever is smaller.

Which I interpret to be that the length of the string does not include the null. That is why I copy len + 1 bytes to include the null, and the test checks to make sure that the length < size of buffer - 2. Minus one because the buffer starts at position 0, and minus another one to make sure there's room for the null.

EDIT: Turns out, the size of something starts with 1 while access starts with 0, so the -2 before was incorrect because it would return an error for anything > 98 bytes but it should be > 99 bytes.

EDIT: Although the answer about a unsigned short is generally correct as the maximum length that can be represented is 65,535 characters, it doesn't really matter because if the string is longer than that, the value will wrap around. It's like taking 75,231 (which is 0x000125DF) and masking off the top 16 bits giving you 9695 (0x000025DF). The only problem that I see with this is the first 100 chars past 65,535 as the length check will allow the copy, but it will only copy up to the first 100 characters of the string in all cases and null terminate the string. So even with the wraparound issue, the buffer still will not be overflowed.

This may or may not in itself pose a security risk depending on the content of the string and what you are using it for. If it's just straight text that is human readable, then there is generally no problem. You just get a truncated string. However, if it's something like a URL or even a SQL command sequence, you could have a problem.

Top answer
1 of 9
35

They did fix the libraries.

Any modern C standard library contains safer variants of strcpy, strcat, sprintf, and so on.

On C99 systems - which is most Unixes - you will find these with names like strncat and snprintf, the "n" indicating that it takes an argument that's the size of a buffer or a maximum number of elements to copy.

These functions can be used to handle many operations more securely, but in retrospect their usability is not great. For example some snprintf implementations don't guarantee the buffer is null-terminated. strncat takes a number of elements to copy, but many people mistakenly pass the size of the dest buffer.

On Windows, one often finds the strcat_s, sprintf_s, the "_s" suffix indicating "safe". These too have found their way into the C standard library in C11, and provide more control over what happens in the event of an overflow (truncation vs. assert for example).

Many vendors provide even more non-standard alternatives like asprintf in the GNU libc, which will allocate a buffer of the appropriate size automatically.

The idea that you can "just fix C" is a misunderstanding. Fixing C is not the problem - and has already been done. The problem is fixing decades of C code written by ignorant, tired, or hurried programmers, or code that has been ported from contexts where security didn't matter to contexts where security does. No changes to the standard library can fix this code, although migration to newer compilers and standard libraries can often help identify the problems automatically.

2 of 9
19

It's not really inaccurate to say that C is actually "error-prone" by design. Aside from some grievous mistakes like gets, the C language can't really be any other way without losing the primary feature that draws people to C in the first place.

C was designed as a systems language to act as a sort of "portable assembly." A major feature of the C language is that unlike higher-level languages, C code often maps very closely to the actual machine code. In other words, ++i is usually just an inc instruction, and you can often get a general idea of what the processor will be doing at run-time by looking at the C code.

But adding in implicit bounds checking adds a lot of extra overhead - overhead which the programmer didn't ask for and might not want. This overhead goes way beyond the extra storage required to store the length of each array, or the extra instructions to check array bounds on every array access. What about pointer arithmetic? Or what if you have a function that takes in a pointer? The runtime environment has no way of knowing if that pointer falls within the bounds of a legitimately allocated memory block. In order to keep track of this, you'd need some serious runtime architecture that can check each pointer against a table of currently allocated memory blocks, at which point we're already getting into Java/C#-style managed runtime territory.