vendredi 29 mai 2015

Is there a memory leak in the following c++ code?

I am writing my program for my DataMining project. I get segmentation error on my code. I tried to debug using the gdb and created core dump using ulimit in ubuntu.

Below is the error I was able to backtrace in gdb.

Python Exception Cannot access memory at address 0x7fff48c47738: #0 0x000000000040cdb0 in TokenReader::getToken ( this=, this@entry=, buf=, buf@entry=) at src/tokread.c++:26 Cannot access memory at address 0x7fff48c47738

My code:



    /*********************************************************
     * Project: 2
     * File: tokread.h
     * Anil Pediredla, KUID 28056
     *********************************************************/

    #ifndef _TOKREAD_H_
    #define _TOKREAD_H_

    #include 
    using namespace std;

    const short NEW_LINE = 0;
    const short SPACE    = 1;
    const short TOKEN    = 2;
    const short COMMENT  = 3;

    class TokenReader {
      public:

        TokenReader(istream &in);

        char* getToken(char* buf);

      private:
        istream ∈
        short state;
    };



    #endif //_TOKREAD_H_

    /*********************************************************
     * Project: 2
     * File: tokread.h
     * Anil Pediredla, KUID 28056
     *********************************************************/

    #include 
    #include 

    using namespace std;

    #include "tokread.h"


    /*********************************************************
     * Class: TokenReader
     *********************************************************/
    TokenReader::TokenReader(istream &in):
      in(in), state(NEW_LINE) {
    }


    char* TokenReader::getToken(char* buf) {
      bool done = false;
      int tokLen = 0;
      while (!done && !in.eof()) {
        char ch = in.get();
        switch (state) {
          case NEW_LINE:
            if (ch == '!') state = COMMENT;
            else {
              in.unget();
              state = SPACE;
            }
          break;
          case SPACE: 
            if ((ch == 13) && (in.peek() == '\n')) in.get();
            if (ch == '\n') {
              state = NEW_LINE;
              break;
            }
            if ((ch != ' ') && (ch != '\t')) {
              in.unget();
              state = TOKEN;
            }
          break;
          case TOKEN:
            if ((ch == 13) && (in.peek() == '\n')) in.get();
            if (ch == '\n') {
              state = NEW_LINE;
              done = true;
              break;
            }
            if ((ch == ' ') || (ch == '\t')) {
              in.unget();
              state = SPACE;
              done = true;
              break;
            }
            buf[tokLen++] = ch;
          break;
          case COMMENT:
           if (ch == '\n'){
               state = NEW_LINE;
           }
          break;
        }
      }
      buf[tokLen] = '\0';
      return buf;
    }


Aucun commentaire:

Enregistrer un commentaire