C++ Core Guidelines: Avoid Bounds Errors

Contents[Show]

When you access an element outside a container of the STL, the result is not so promising. You effect may be an error or undefined behaviour. Undefined behaviour means all bets are open.

 

brno 2783268 1280

 

First of all: What is a bounds error? A bounds error happens when you read or write beyond the elements of a container. The result is different depending on the used container. Of course, the C++ core guidelines is very concrete.

SL.con.3: Avoid bounds errors

The C++ core guidelines starts with a bad example which uses the unsafe C-functions to fill and compare a std::array.

std::array<int, 10> a, b;
std::memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
std::memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))

 

The comments to the code already say it. The length of the C-arrays is not 10 but 10 * sizeof(int). The solution is obvious. Use the functionality of the std::array.

 

std::array<int, 10> a;
std::array<int, 10> b;

std::array<int, 10> c{};           

a.fill(0);                         // (1)
std::fill(b.begin(), b.end(), 0);  // (2)  

if ( a == b ){                     // (3)
    // ...
}

In this case, the std::array a and b are not initialised. In opposite, all values of c are initialised to 0. Line (1) sets all values of a to 0 and line 2 does the same by using the function templates std::fill. Comparison is also quite convenient (line 3).

Using a container outsides its range is in general undefined behaviour. Let me see what that means.

Bounds Errors

The most elementary sequential container we have in C++ is the C-array.

C-Array

The effect of an overflow or an underflow is the same: memory corruption and undefined behaviour. Let's make a simple test with an int array. How long will the next program run?

// overUnderflow.cpp

#include <cstddef>
#include <iostream>

int main(){
    
    int a[0];
    int n{};

    while (true){
        if (!(n % 100)){
            std::cout << "a[" << n << "] = " << a[n] << ", a[" << -n << "] = " << a[-n] << "\n";
        }
        a[n] = n;
        a[-n] = -n;
        ++n;
    }
    
}

 

Way too long! The program writes each 100th array entry to std::cout. 

overUnderflow

Okay, what will happen if I use a sequential container from the STL? Here we are:

Sequential Containers of the STL

The index operator is available for std::array, std::vector, std::deque, and std::string. For simplicity reasons, I count a std::string as a sequential container. This means, all containers support random access and return a random access iterator. To bore you not to death I use in my next experiment only a std::array and a std::vector

std::array

This is the modified program for std::array:

// overUnderflowStdArray.cpp

#include <array>
#include <iostream>

int main(){
    
    std::array<int, 1> a;
    int n{};

    while (true){
        if (!(n % 100)){
            std::cout << "a[" << n << "] = " << a[n] << 
                       ", a[" << -n << "] = " << a[-n] << "\n";
        }
        a[n] = n;
        a[-n] = -n;
        ++n;
    }
    
}

Using the index operator for a C++-array is not better than using it for a C-array.

overUnderflowStdArray

Maybe, a std::vector comes to our rescue.

std::vector

 

// overUnderflowStdVector.cpp

#include <vector>
#include <iostream>

int main(){
    
    std::vector<int> a{1};
    int n{};

    while (true){
        if (!(n % 100)){
            std::cout << "a[" << n << "] = " << a[n] << 
                       ", a[" << -n << "] = " << a[-n] << "\n";
        }
        a[n] = n;
        a[-n] = -n;
        ++n;
    }
    
}

 

Because the std::vector creates its objects on the heap and not on the stack such as the C- and C++-array, it takes quite a while for the program to fail. The screenshots show the begin and the end of the under- and overflow.

overUnderflowStdVector1

 

overUnderflowStdVector2

 

 

 

 

 

 

 

 

 

 

 

 

Additionally, the associative containers such as std::map and std::unordered_map also support the index operator.

Associative Containers of the STL

What happens, when you use a non-existing key in a std::map or std::unordered_map?

 

// indexOperatorMapAndUnorderedMap.cpp

#include <iostream>
#include <map>
#include <unordered_map>
#include <string>

int main(){

    std::cout << std::boolalpha << std::endl;

    std::map<std::string, int> myMap;
    std::unordered_map<std::string, bool> myUnorderedMap;
	
    std::cout << "myMap[DoesNotExist]: " << myMap["DoesNotExist"] << std::endl;
	
    std::cout << "myUnorderedMap[DoesNotExist]: " << myUnorderedMap["DoesNotExist"] << std::endl;
	
}

 

In case of the associative container, the value you get is well-defined if the key is not available. The value has to be DefaultConstructible because the default constructor is invoked if the key is not available. This creates der literal 0 in the first case and the literal false in the second case.

indexOperatorMapAndUnorderedMap

Okay, the essential question of the guideline remains: How can you avoid bounds errors?

Avoid bounds errors

In case of the C-array there is no rescue to detect a bounds error. For the C++ containers including std::string there is the method at which checks the bounds. All C++ container throw a std::out_of_range exception if you access a non-exsiting element of the container. The std::string shows this impressive.

 

// stringBoundsCheck.cpp

#include <stdexcept>
#include <iostream>
#include <string>
 
int main(){

    std::cout << std::endl;

    std::string str("1123456789"); 
 
    str.at(0) = '0';                                   // (1)
    
    std::cout << str << std::endl;
 
    std::cout << "str.size(): " << str.size() << '\n';
    std::cout << "str.capacity() = " << str.capacity() << '\n';
 
    try {
        str.at(12) = 'X';                              // (2)
    }
    catch (const std::out_of_range& exc) {
        std::cout << exc.what() << std::endl;
    }
    
    std::cout << std::endl;

}
    

 

Setting the first character of the string str to '0' (line 1) is fine, but accessing a character outside the size is an error. This even holds if the access is within the capacity but outside the size of the std::string.

  1. The size of a std::string is the number of elements the std::string has.
  2. The capacity of a std::string is the number of elements a std::string could have without allocating additional memory. 

The error message of the windows compiler 19.20 is unspecific.

stringBoundsCheckWin

The error message for the GCC 8.2 is quite specific.

stringBoundsCheck

What's next?

This post was the last one to the containers of the STL. The next post is about the various string types.

 

 

 

Thanks a lot to my Patreon Supporters: Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, Ramesh Jangama, G Prvulovic, Reiner Eiteljörge, Benjamin Huth, Reinhold Dröge, Timo, Abernitzke, Richard Ohnemus , Frank Grimm, Sakib, and Broeserl.

Thanks in particular to:  TakeUpCode 450 60     crp4

 

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Get your interactive course

 

Modern C++ Concurrency in Practice

C++ Standard Library including C++14 & C++17

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 1707

All 2289808

Currently are 152 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments