More char * madness.


R. Clayton (rclayton@monmouth.edu)
Tue, 18 Jul 2000 16:18:30 -0400 (EDT)


Another of your colleagues wrote the following code in their dequeue
assignment, presumably with the intention of splitting the string imp into
words and storing each word in the strings field and word:

  // blah blah blah

  string inp;

  // blah blah blah

  getline(cin, inp);

  // blah blah blah

  char * inp_tmp = new char[inp.length() + 1];
  char * tmp[3];

  // blah blah blah

  strcpy(imp_tmp, imp.c_str());
  tmp[0] = strtok(inp_tmp, " ");
  delete [] inp_tmp;
  int i = 0;
  while (tmp[i] != NULL)
    tmp[++i] = strtok(NULL, " ");

  // blah blah blah

  sting field(tmp[1]), word(tmp[2]);

Unfortunately, when this code is run, both field and word are the empty
string. Can you figure out why?

The insidious thing about this programming error is that it depends on the way
in which the host system manages storage. On this particular colleague's host
system, the error apparently didn't manifest itself due to the fortunate way in
which the host system managed storage. However, the program was less fortunate
on the system I use for testing.

Before you assume that your colleague's system is better than my system, you
should keep in mind that it's easy to change the way a system manages storage.
All you need to do is allocate a object before executing the code above, or not
allocate an object, or allocate a larger object, or allocate a smaller object,
or run the program on a smaller version of the system or run the program on a
larger version or . . .



This archive was generated by hypermail 2.0b3 on Fri Aug 11 2000 - 15:25:05 EDT