Home > Articles > Programming > C/C++

This chapter is from the book

2.2. Common String Manipulation Errors

Manipulating strings in C or C++ is error prone. Four common errors are unbounded string copies, off-by-one errors, null-termination errors, and string truncation.

Improperly Bounded String Copies

Improperly bounded string copies occur when data is copied from a source to a fixed-length character array (for example, when reading from standard input into a fixed-length buffer). Example 2.1 shows a program from Annex A of ISO/IEC TR 24731-2 that reads characters from standard input using the gets() function into a fixed-length character array until a newline character is read or an end-of-file (EOF) condition is encountered.

Example 2.1. Reading from stdin()

01  #include <stdio.h>
02  #include <stdlib.h>
04  void get_y_or_n(void) {
05    char response[8];
06    puts("Continue? [y] n: ");
07    gets(response);
08    if (response[0] == 'n')
09      exit(0);
10    return;
11  }

This example uses only interfaces present in C99, although the gets() function has been deprecated in C99 and eliminated from C11. The CERT C Secure Coding Standard [Seacord 2008], “MSC34-C. Do not use deprecated or obsolescent functions,” disallows the use of this function.

This program compiles and runs under Microsoft Visual C++ 2010 but warns about using gets() at warning level /W3. When compiled with G++ 4.6.1, the compiler warns about gets() but otherwise compiles cleanly.

This program has undefined behavior if more than eight characters (including the null terminator) are entered at the prompt. The main problem with the gets() function is that it provides no way to specify a limit on the number of characters to read. This limitation is apparent in the following conforming implementation of this function:

01  char *gets(char *dest) {
02    int c = getchar();
03    char *p = dest;
04    while (c != EOF && c != '\n') {
05      *p++ = c;
06      c = getchar();
07    }
08    *p = '\0';
09    return dest;
10  }

Reading data from unbounded sources (such as stdin()) creates an interesting problem for a programmer. Because it is not possible to know beforehand how many characters a user will supply, it is not possible to preallocate an array of sufficient length. A common solution is to statically allocate an array that is thought to be much larger than needed. In this example, the programmer expects the user to enter only one character and consequently assumes that the eight-character array length will not be exceeded. With friendly users, this approach works well. But with malicious users, a fixed-length character array can be easily exceeded, resulting in undefined behavior. This approach is prohibited by The CERT C Secure Coding Standard [Seacord 2008], “STR35-C. Do not copy data from an unbounded source to a fixed-length array.”

Copying and Concatenating Strings

It is easy to make errors when copying and concatenating strings because many of the standard library calls that perform this function, such as strcpy(), strcat(), and sprintf(), perform unbounded copy operations.

Arguments read from the command line are stored in process memory. The function main(), called when the program starts, is typically declared as follows when the program accepts command-line arguments:

1  int main(int argc, char *argv[]) {
2      /* ...*/
3  }

Command-line arguments are passed to main() as pointers to null-terminated strings in the array members argv[0] through argv[argc-1]. If the value of argc is greater than 0, the string pointed to by argv[0] is, by convention, the program name. If the value of argc is greater than 1, the strings referenced by argv[1] through argv[argc-1] are the actual program arguments. In any case, argv[argc] is always guaranteed to be NULL.

Vulnerabilities can occur when inadequate space is allocated to copy a program input such as a command-line argument. Although argv[0] contains the program name by convention, an attacker can control the contents of argv[0] to cause a vulnerability in the following program by providing a string with more than 128 bytes. Furthermore, an attacker can invoke this program with argv[0] set to NULL:

1  int main(int argc, char *argv[]) {
2    /* ... */
3    char prog_name[128];
4    strcpy(prog_name, argv[0]);
5    /* ... */
6  }

This program compiles and runs under Microsoft Visual C++ 2012 but warns about using strcpy() at warning level /W3. The program also compiles and runs under G++ 4.7.2. If _FORTIFY_SOURCE is defined, the program aborts at runtime as a result of object size checking if the call to strcpy() results in a buffer overflow.

The strlen() function can be used to determine the length of the strings referenced by argv[0] through argv[argc-1] so that adequate memory can be dynamically allocated. Remember to add a byte to accommodate the null character that terminates the string. Note that care must be taken to avoid assuming that any element of the argv array, including argv[0], is non-null.

01  int main(int argc, char *argv[]) {
02    /* Do not assume that argv[0] cannot be null */
03    const char * const name = argv[0] ? argv[0] : "";
04    char *prog_name = (char *)malloc(strlen(name) + 1);
05    if (prog_name != NULL) {
06      strcpy(prog_name, name);
07    }
08    else {
09        /* Failed to allocate memory - recover */
10    }
11    /* ... */
12  }

The use of the strcpy() function is perfectly safe because the destination array has been appropriately sized. It may still be desirable to replace the strcpy() function with a call to a “more secure” function to eliminate diagnostic messages generated by compilers or analysis tools.

The POSIX strdup() function can also be used to copy the string. The strdup() function accepts a pointer to a string and returns a pointer to a newly allocated duplicate string. This memory can be reclaimed by passing the returned pointer to free(). The strdup() function is defined in ISO/IEC TR 24731-2 [ISO/IEC TR 24731-2:2010] but is not included in the C99 or C11 standards.

sprintf() Function

Another standard library function that is frequently used to copy strings is the sprintf() function. The sprintf() function writes output to an array, under control of a format string. A null character is written at the end of the characters written. Because sprintf() specifies how subsequent arguments are converted according to the format string, it is often difficult to determine the maximum size required for the target array. For example, on common ILP32 and LP64 platforms where INT_MAX = 2,147,483,647, it can take up to 11 characters to represent the value of an argument of type int as a string (commas are not output, and there might be a minus sign). Floating-point values are even more difficult to predict.

The snprintf() function adds an additional size_t parameter n. If n is 0, nothing is written, and the destination array may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than written to the array, and a null character is written at the end of the characters that are actually written into the array. The snprintf() function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Consequently, the null-terminated output is completely written if and only if the returned value is nonnegative and less than n. The snprintf() function is a relatively secure function, but like other formatted output functions, it is also susceptible to format string vulnerabilities. Values returned from snprintf() need to be checked because the function may fail, not only because of insufficient space in the buffer but for other reasons as well, such as out-of-memory conditions during the execution of the function. See The CERT C Secure Coding Standard [Seacord 2008], “FIO04-C. Detect and handle input and output errors,” and “FIO33-C. Detect and handle input output errors resulting in undefined behavior,” for more information.

Unbounded string copies are not limited to the C programming language. For example, if a user inputs more than 11 characters into the following C++ program, it will result in an out-of-bounds write:

1  #include <iostream>
3  int main(void) {
4    char buf[12];
6    std::cin >> buf;
7    std::cout << "echo: " << buf << '\n';
8  }

This program compiles cleanly under Microsoft Visual C++ 2012 at warning level /W4. It also compiles cleanly under G++ 4.7.2 with options: -Wall -Wextra -pedantic.

The type of the standard object std::cin is the std::stream class. The istream class, which is really a specialization of the std::basic_istream class template on the character type char, provides member functions to assist in reading and interpreting input from a stream buffer. All formatted input is performed using the extraction operator operator>>. C++ defines both member and nonmember overloads of operator>>, including

istream& operator>> (istream& is, char* str);

This operator extracts characters and stores them in successive elements of the array pointed to by str. Extraction ends when the next element is either a valid white space or a null character or EOF is reached. The extraction operation can be limited to a certain number of characters (avoiding the possibility of buffer overflow) if the field width (which can be set with ios_base::width or setw()) is set to a value greater than 0. In this case, the extraction ends one character before the count of characters extracted reaches the value of field width, leaving space for the ending null character. After a call to this extraction operation, the value of the field width is automatically reset to 0. A null character is automatically appended after the extracted characters.

The extraction operation can be limited to a specified number of characters (thereby avoiding the possibility of an out-of-bounds write) if the field width inherited member (ios_base::width) is set to a value greater than 0. In this case, the extraction ends one character before the count of characters extracted reaches the value of field width, leaving space for the ending null character. After a call to this extraction operation, the value of the field width is reset to 0.

The program in Example 2.2 eliminates the overflow in the previous example by setting the field width member to the size of the character array buf. The example shows that the C++ extraction operator does not suffer from the same inherent flaw as the C function gets().

Example 2.2. Field width Member

1  #include <iostream>
3  int main(void) {
4    char buf[12];
6    std::cin.width(12);
7    std::cin >> buf;
8    std::cout << "echo: " << buf << '\n';
9  }

Off-by-One Errors

Off-by-one errors are another common problem with null-terminated strings. Off-by-one errors are similar to unbounded string copies in that both involve writing outside the bounds of an array. The following program compiles and links cleanly under Microsoft Visual C++ 2010 at /W4 and runs without error on Windows 7 but contains several off-by-one errors. Can you find all the off-by-one errors in this program?

01  #include <string.h>
02  #include <stdio.h>
03  #include <stdlib.h>
05  int main(void) {
06    char s1[] = "012345678";
07    char s2[] = "0123456789";
08    char *dest;
09    int i;
11    strcpy_s(s1, sizeof(s2), s2);
12    dest = (char *)malloc(strlen(s1));
13    for (i=1; i <= 11; i++) {
14      dest[i] = s1[i];
15    }
16    dest[i] = '\0';
17    printf("dest = %s", dest);
18    /* ... */;
19  }

Many of these mistakes are rookie errors, but experienced programmers sometimes make them as well. It is easy to develop and deploy programs similar to this one that compile and run without error on most systems.

Null-Termination Errors

Another common problem with strings is a failure to properly null-terminate them. A string is properly null-terminated if a null terminator is present at or before the last element in the array. If a string lacks the terminating null character, the program may be tricked into reading or writing data outside the bounds of the array.

Strings must contain a null-termination character at or before the address of the last element of the array before they can be safely passed as arguments to standard string-handling functions, such as strcpy() or strlen(). The null-termination character is necessary because these functions, as well as other string-handling functions defined by the C Standard, depend on its existence to mark the end of a string. Similarly, strings must be null-terminated before the program iterates on a character array where the termination condition of the loop depends on the existence of a null-termination character within the memory allocated for the string:

1  size_t i;
2  char ntbs[16];
3  /* ... */
4  for (i = 0; i < sizeof(ntbs); ++i) {
5    if (ntbs[i] == '\0') break;
6    /* ... */
7  }

The following program compiles under Microsoft Visual C++ 2010 but warns about using strncpy() and strcpy() at warning level /W3. It is also diagnosed (at runtime) by GCC on Linux when the _FORTIFY_SOURCE macro is defined to a nonzero value.

1  int main(void) {
2    char a[16];
3    char b[16];
4    char c[16];
5    strncpy(a, "0123456789abcdef", sizeof(a));
6    strncpy(b, "0123456789abcdef", sizeof(b));
7    strcpy(c, a);
8    /* ... */
9  }

In this program, each of three character arrays—a[], b[], and c[]—is declared to be 16 bytes. Although the strncpy() to a is restricted to writing sizeof(a) (16 bytes), the resulting string is not null-terminated as a result of the historic and standard behavior of the strncpy() function.

According to the C Standard, the strncpy() function copies not more than n characters (characters that follow a null character are not copied) from the source array to the destination array. Consequently, if there is no null character in the first n characters of the source array, as in this example, the result will not be null-terminated.

The strncpy() to b has a similar result. Depending on how the compiler allocates storage, the storage following a[] may coincidentally contain a null character, but this is unspecified by the compiler and is unlikely in this example, particularly if the storage is closely packed. The result is that the strcpy() to c may write well beyond the bounds of the array because the string stored in a[] is not correctly null-terminated.

The CERT C Secure Coding Standard [Seacord 2008] includes “STR32-C. Null-terminate byte strings as required.” Note that the rule does not preclude the use of character arrays. For example, there is nothing wrong with the following program fragment even though the string stored in the ntbs character array may not be properly null-terminated after the call to strncpy():

1  char ntbs[NTBS_SIZE];
3  strncpy(ntbs, source, sizeof(ntbs)-1);
4  ntbs[sizeof(ntbs)-1] = '\0';

Null-termination errors, like the other string errors described in this section, are difficult to detect and can lie dormant in deployed code until a particular set of inputs causes a failure. Code cannot depend on how the compiler allocates memory, which may change from one compiler release to the next.

String Truncation

String truncation can occur when a destination character array is not large enough to hold the contents of a string. String truncation may occur while the program is reading user input or copying a string and is often the result of a programmer trying to prevent a buffer overflow. Although not as bad as a buffer overflow, string truncation results in a loss of data and, in some cases, can lead to software vulnerabilities.

String Errors without Functions

Most of the functions defined in the standard string-handling library <string.h>, including strcpy(), strcat(), strncpy(), strncat(), and strtok(), are susceptible to errors. Microsoft Visual Studio, for example, has consequently deprecated many of these functions.

However, because null-terminated byte strings are implemented as character arrays, it is possible to perform an insecure string operation even without invoking a function. The following program contains a defect resulting from a string copy operation but does not call any string library functions:

01  int main(int argc, char *argv[]) {
02    int i = 0;
03    char buff[128];
04    char *arg1 = argv[1];
05    if (argc == 0) {
06      puts("No arguments");
07      return EXIT_FAILURE;
08    }
10    while (arg1[i] != '\0') {
11      buff[i] = arg1[i];
12      i++;
13    }
14    buff[i] = '\0';
15    printf("buff = %s\n", buff);
16    exit(EXIT_SUCCESS);
17  }

The defective program accepts a string argument, copies it to the buff character array, and prints the contents of the buffer. The variable buff is declared as a fixed array of 128 characters. If the first argument to the program equals or exceeds 128 characters (remember the trailing null character), the program writes outside the bounds of the fixed-size array.

Clearly, eliminating the use of dangerous functions does not guarantee that your program is free from security flaws. In the following sections you will see how these security flaws can lead to exploitable vulnerabilities.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020

Sign Up for Our Newsletters

Subscribing to the InformIT newsletters is an easy way to keep in touch with what's happening in your corner of the industry. We have a newsletters dedicated to a variety of topics such as open source, programming, and web development, so you get just the information you need. Sign up today.