Pointer bug

The following snippet of code behaves unpredictably: it will often print a value for testInt which is different from 1, although in the variable testInt is never explicitly changed. Debug the program using ddd and valgrind. What is the bug? How can you fix it? Change the order of the statements marked (a), (b), (c) and test the resulting programs: what is the behaviour? Can you explain it?


// this program is buggy!
#include<iostream>
#include<cstring>

const int bufSize = 20;

int main(int argc, char** argv) {
  using namespace std;
  if (argc < 3) {
    cerr << "need a char and a word as arguments on cmd line" << endl;
    return 1;
  }
  
  // a test integer to which we assign the value 1
  int testInt = 1;                                 // (a)

  // get the first char of the first argument
  char theChar = argv[1][0];                       // (b)

  // get the second argument as word
  char buffer[bufSize];                            // (c)
  strncpy(buffer, argv[2], bufSize);
  char* wordPtr = buffer;

  // skip characters in the word and delete them, until we find theChar
  while(*wordPtr != theChar) {
    *wordPtr = ' ';
    wordPtr++; 
    cout << (int) (wordPtr - buffer) << endl;
  }

  // now see what value has the test integer
  cout << testInt << endl;
  return 0;
}



Subsections

Leo Liberti 2008-01-12