Thread: making a bug apparent

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    569

    making a bug apparent

    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");
    }
    Last edited by -EquinoX-; 02-27-2010 at 11:23 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Disappearing Bug
    By el-sid in forum C++ Programming
    Replies: 4
    Last Post: 08-16-2009, 12:12 PM
  2. compiler bug or brain bug?
    By Lesshardtofind in forum C++ Programming
    Replies: 10
    Last Post: 07-14-2009, 03:16 AM
  3. multithread bug I cannot reproduce
    By CodeMonkey in forum C++ Programming
    Replies: 9
    Last Post: 06-10-2009, 07:34 PM
  4. Kernel bug? (attn matsp)
    By brewbuck in forum Linux Programming
    Replies: 7
    Last Post: 04-13-2009, 10:31 AM
  5. Zooming Algorithm Bug
    By stuffy_boiz in forum C Programming
    Replies: 2
    Last Post: 01-19-2009, 02:34 AM