Memory Access Violation

// This program has been carefully crafted to serve
// a certain purpose:
// 1. It has a memory access violation.
// 2. It does not have any other construct that
//    qualifies for a compiler warning.
// 3. Function process_names() is a quite convincing
//    situation that tries to mimic a real life proc.
// 4. No headers included to minimize static analyzer
//    reports.
// 5. It is written in C++03, so that an old static
//    analyzer can deal with it.

// mock structure to represent a processed file contents
struct Names
{
  const char * list[3];
};

// mock string class
//  It does not check for a null pointer before 
//  the 1st dereference. 
struct MyString
{
  char str [64];
 
  MyString(const char * s)
    : str() // zero-initialize the array
  {
    for (int i = 0 ; *s != 0 ; ++s)
      str[i++] = *s;
  }
};

typedef MyString  String;

// mock logging statement
void log(String const& /*filename*/, const char * /*val*/) {}

// mock file parser
Names parse_file (String const& filename)
{
  Names ans;
  (void)filename; // mock opening of a  file
  ans.list[0] = "A";
  ans.list[1] = "B";
  ans.list[2] = "C";
  return ans;
}

// the function with the bug
void process_names()
{
  const char * foundName = 0;
  const char * fileName = "contents.txt";

  Names names = parse_file(foundName);
  foundName = names.list[1]; // mock search
  log(fileName, foundName);
}

int main()
{
  process_names();
}
Advertisements