My instructor said that if the writer of the code below made full use a language feature in C++ from one of the following:
References
The const qualifier
NULL vs. 0
bool
The friend specifier
Copy constructors
the bug would be apparent to see.... do you guys have any idea what it is?
I know the problem is clearly at the get method and the itsChars variable.. but what feature would make the bug apparent?
Code:
#include <cstdio>
#include <cstring>
#include <cstdlib>
class CharList {
public:
CharList(char* s) {
itsChars = new char[strlen(s)+1];
strcpy(itsChars, s);
}
//
// Iterate over the characters, returning a NUL when done
//
char get() {
if (*itsChars)
return *itsChars++;
else
return 0;
}
//
// Return the nth character
//
char at(int n) {
if (n < length())
return itsChars[n];
else
return 0;
}
int length() { return strlen(itsChars); }
private:
char *itsChars;
};
//
// debugging routine -- print the characters in the list
//
void print(const char *label, CharList& L)
{
printf("%s", label);
const char *fmt = "%c";
while (char c = L.get()) {
printf(fmt, c);
fmt = ", %c";
}
puts("");
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: %s STRING\n", argv[0]);
exit(1);
}
CharList L(argv[1]);
print("argv[1]: ", L);
printf("Ready to enter loop...\n");
for (int i = 0; i < L.length(); i++) {
printf("in loop\n");
printf("L[%d] = '%c'\n", i, L.at(i));
}
printf("Done with loop...\n");
}