Skip to content

Lesson 1 of 2

Memory errors in C and C++

Listen to an AI summary of Memory errors in C and C++

0:00 / 0:33

A running program keeps its data in the computer's memory. Python stops a program that writes past the end of a list. C and C++ are two older programming languages, used for operating systems and games, that make no such check.

What is a buffer

A buffer is a block of memory set aside to hold some data, such as a name. A C program says how many characters each buffer holds, and the size never changes.

A buffer works like a row of ten numbered boxes on a paper form, with one letter in each box. Each box is one position in the buffer, and the next row on the form is the memory next to the buffer. A person who writes a word of twelve letters stops at the tenth box. C does not stop, and writes the last two letters over the next row.

A user id in the sports shop

One part of the sports shop website is written in C. The C code keeps the user id of the person who is signed in, and that person's role. The role is buyer or staff, and staff can see every order.

The function save_user_id receives input, a user id from a request. Look at line 4.

  1. char user_id[10];// sets aside a buffer of 10 characters named user_id. char is the C word for a character.
  2. char role[10];// sets aside a second buffer. In this program, role sits right after user_id in memory.
  3. void save_user_id(char *input) {// Line 3 starts a function. void means the function returns no value, and char *input is a string named input. Python writes def save_user_id(input):
  4. strcpy(user_id, input);// copies the string input into user_id. Python writes user_id = input
  5. }// ends the function
The C code that saves a user id.

C marks the end of every string with one extra character, the end mark, written \0. strcpy copies every character of input up to the end mark. strcpy never looks at the size of user_id.

What a long user id does

Sam signs in with the user id sam04, and the role is buyer. Sam then sends a request with a user id of 15 characters, aaaaaaaaaastaff.

  1. user_id s a m 0 4 \0 . . . .Before. The buffer holds sam04 and the end mark.
  2. role b u y e r \0 . . . .Before. The next buffer holds buyer and the end mark.
  3. user_id a a a a a a a a a aAfter. Ten letters fill the buffer.
  4. role s t a f f \0 . . . .After. The last five letters and the end mark land here.
The two buffers before and after the copy. A dot is an unused position.

strcpy keeps copying after the tenth letter, so staff and the end mark land in role. The program now reads the role as staff, and Sam can see every order.

What is a buffer overrun

A buffer overrun is writing more data than a buffer can hold, so that the extra data lands in the memory beside the buffer. The CWE list names a buffer overrun out-of-bounds write (CWE-787).

A buffer overrun can also make the program crash. An attacker who chooses the extra data with care can make the program run the attacker's own code.

What is a bounds check

A bounds check is code that confirms a position is inside a buffer or an array before reading or writing. The safer code checks the length of input before the copy. Look at line 2.

  1. void save_user_id(char *input) {// starts the function
  2. if (strlen(input) > 9) {// is the bounds check. strlen counts the characters in a string, like len in Python.
  3. return;// leaves the function, so a long user id is never copied
  4. }// ends the if
  5. strcpy(user_id, input);// copies a user id of 9 characters or fewer
  6. }// ends the function
The safer code that saves a user id.

The check on line 2 uses 9 because the tenth position holds the end mark.

strcpy, strcat, sprintf and gets are C functions that write text into a buffer with no bounds check. Functions that take the size of the buffer, such as snprintf, are safer. strncpy also takes a size, but adds no end mark when the text fills the buffer.

What is an off-by-one error

An off-by-one error is a count or a position that is wrong by one. C numbers the positions of an array from 0, as Python numbers a list. An array of 100 values has positions 0 to 99.

[0][1]…[98][99][100]

  1. [0]first
  2. [99]last
  3. [100]past the end
An array of 100 values. A write to position 100 lands in the memory after the array.

The bounds check in the sports shop can have the same error. A check of > 10 in place of > 9 accepts a user id of 10 characters. The 10 characters fill the buffer, and the end mark overwrites the first character of role.

Memory-safe languages

A memory-safe language is a programming language that makes a bounds check on every read and write. Python, Java, JavaScript, Ruby, Go and Rust are memory-safe languages. The two lines of Python write past the end of a list.

user_id = ["a"] * 10    # ten copies of "a", positions 0 to 9
user_id[10] = "s"       # IndexError: list assignment index out of range

Python stops the program with an error and writes nothing. Code in a memory-safe language can still run code written in C. Rust and Go code can also skip the checks with the word unsafe. A reviewer reads both kinds of code as closely as C.

Format strings

printf is a C function that prints text, like print in Python. A format string is a string that tells a function how to turn values into text, using marks such as %d. The line of C prints You ordered 3 tickets when quantity holds 3.

printf("You ordered %d tickets", quantity);

printf replaces the mark %d with a number, and the mark %s with a string. The next two lines print input, a string from a request. Look at what comes first inside the brackets.

printf(input);          // a weakness. The input is the format string
printf("%s", input);    // safer. The input is a value to print

On the first line, printf acts on every mark in input. An attacker types the three marks %x %x %x, and printf prints three values from the program's memory. The mark %n makes printf write to memory.

On the second line, printf prints the marks in input as plain text. Input used as the format string is use of externally-controlled format string (CWE-134).

Integer overflow

C stores a whole number in a fixed number of bits. A number stored in 8 bits holds 0 to 255 and has no room for 256, so adding 1 to 255 gives 0. A number stored in 32 bits wraps round the same way at about 4 billion.

Integer overflow (CWE-190) is a result too big for the space a number is stored in. The number wraps round to a small value.

The sports shop sets aside memory for a list of tickets. Each ticket needs 16 bytes of memory, and count is a number from a request. malloc is a C function that sets aside a buffer of a given size. Look at the multiplication on each line.

tickets = malloc(count * 16);   // wraps round when count is very large
tickets = calloc(count, 16);    // safer. calloc checks the multiplication

A very large count makes count * 16 wrap round to a small number, so malloc sets aside a small buffer. The loop that fills in count tickets then writes past the end of the buffer. calloc does the multiplication, and returns no buffer when the result overflows.

A bounds check with one end

A number in C can be negative, so a bounds check has two ends. The code writes to an array of 100 seats at a seat number from a request. Look at what the if leaves out.

if (seat > 99) {
    return;          // the seat number is too big
}
seats[seat] = 1;     // a seat number of -5 writes before the array

A seat number of -5 is not above 99, so the check passes. The write lands before the start of the array. Safer code also refuses a seat number below 0.

Examples of what to look for

  • A line that uses strcpy, strcat, sprintf or gets, which make no bounds check.
  • A write into a buffer or an array at a position from a request, with no bounds check.
  • A check or a loop that is out by one, such as <= where < belongs.
  • A buffer with no position for the end mark.
  • A printf line whose format string is a variable, such as printf(input).
  • A number from a request multiplied to give the size for malloc.
  • A bounds check with a top end and no bottom end, such as seat > 99 alone.
  • The word unsafe in Rust, or C code run from a memory-safe language.

Check your understanding

  1. State the last valid position in an array of 100 values.

    Show the answer

    Position 99. C numbers positions from 0.

  2. Which line of the sports shop's first C example copies the user id with no bounds check?

    Show the answer

    Line 4, strcpy(user_id, input);. strcpy never looks at the size of user_id.

  3. Give one reason why the user id aaaaaaaaaastaff changes the role to staff.

    Show the answer

    The buffer user_id holds 10 characters, so the extra data lands in role, the memory beside the buffer.

Practise it

Challenges with a weakness this lesson teaches.