Memory failures in C++ maps
I noticed that there is a certain danger when we use the C++ maps to look up a key that was missing. When a missing key is looked up from a map, this actually affects the size() of the map, leading to unexpected secondary bugs when this map is later used again.
Here is a test code and its output to visualize what is going on:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <cstring>
#include <sstream>
#include <string>
#include <string.h>
#include <vector>
#include <map>
using namespace std;
map<string, int> testMap;
int main()
{
testMap["a"]=4;
testMap["b"]=5;
testMap["c"]=6;
testMap["d"]=7;
testMap["e"]=8;
testMap["f"]=9;
testMap["g"]=10;
testMap["h"]=11;
testMap["k"]=12;
testMap["l"]=13;
vector<string> vec_st;
vec_st.push_back("a");
vec_st.push_back("b");
vec_st.push_back("c");
vec_st.push_back("d");
vec_st.push_back("e");
vec_st.push_back("f");
vec_st.push_back("g");
vec_st.push_back("h");
vec_st.push_back("k");
vec_st.push_back("l");
int firstSize = testMap.size();
cout << "Before the search for missing key m, we have testMap.size() = " << firstSize << endl;
cout << "Values of the map before the attempt to look up missing key: " << endl;
for(int i=0; i < testMap.size(); i++)
{
cout << "testMap[vec_st["<<i<<"] ] = " << testMap[vec_st[i] ] << endl;
}
string s = "m";
int j2 = testMap[s] ; // Questionable attempt to find a missing key's value
cout << "s = " << s << " , but after this questionable lookup of s, we get testMap[s] = " << j2 << endl;
int secondSize = testMap.size();
cout << "Size AFTER the search for missing key m = " << secondSize << endl;
cout << " After the attempt to look up a missing key we get: " << endl;
for(int i=0; i< testMap.size(); i++)
{
cout << "testMap[vec_st["<<i<<"] ] = " << testMap[vec_st[i] ]<< endl;
}
// Better safeguard: use the ::count() function to check that the key exists in the first place:
// Write: if(testMap.count(s) >0) { j2=testMap[s] ; }
}
Here is the output that shows that the attempt to look up a missing key results in the alteration of the size of the map, an alteration of the memory:
Before the search for missing key m, we have testMap.size() = 10
Values of the map before the attempt to look up missing key:
testMap[vec_st[0] ] = 4
testMap[vec_st[1] ] = 5
testMap[vec_st[2] ] = 6
testMap[vec_st[3] ] = 7
testMap[vec_st[4] ] = 8
testMap[vec_st[5] ] = 9
testMap[vec_st[6] ] = 10
testMap[vec_st[7] ] = 11
testMap[vec_st[8] ] = 12
testMap[vec_st[9] ] = 13
s = m , but after this questionable lookup of s, we get testMap[s] = 0
Size AFTER the search for missing key m = 11
After the attempt to look up a missing key we get:
testMap[vec_st[0] ] = 4
testMap[vec_st[1] ] = 5
testMap[vec_st[2] ] = 6
testMap[vec_st[3] ] = 7
testMap[vec_st[4] ] = 8
testMap[vec_st[5] ] = 9
testMap[vec_st[6] ] = 10
testMap[vec_st[7] ] = 11
testMap[vec_st[8] ] = 12
testMap[vec_st[9] ] = 13
Segmentation fault (core dumped)