Solved

string variable problem in UNIX Env (PRO *C)

Posted on 2004-03-28
7
359 Views
Last Modified: 2013-12-26
I am having a variable of type string (string m_str). The problem is it is able to add to m_str till the length of m_str reaches 300 / 400 and beyond that the program hangs. I wants to store more than 1000 / 2000 characters. I tried resize (m_str.resize()) but this works at some places and does not work at some places. Why it is not able to add beyond 300 / 400 characters. Code is below

StringUtil& StringUtil::operator=(const StringUtil& src)
{
    m_str = src.m_str;                  //This gives problem
    m_initialized = src.m_initialized;

    return *this;
}

int StringUtil::fillData(int iPos,char* cTemp) function also gives problem.

i tried with std::string and removed all resizing, but still giving the same problem.

Whole code is below:
Below is the code of StringUtil.cpp and StringUtil.h


//******* STRINGUTIL.CPP *************

#include "StringUtil.h"
#include <string.h>
#include <stdlib.h>
#ifdef WIN32
#include <tchar.h>
#endif
#include <string>


StringUtil::StringUtil()
{
    m_initialized = true;
}

StringUtil::StringUtil (const long int& src)
{
    char *buf =new char[MAX_STRING_SIZE];
    sprintf(buf,"%ld",src);
    m_str = buf;
    m_initialized = true;
    delete buf;

}

StringUtil::StringUtil (const string& src)
{
    m_str = src;

}
StringUtil::StringUtil (const char* src)
{
    string tmpStr(src);
    m_str = tmpStr;
}

StringUtil::StringUtil(const StringUtil& objStringUtil)
{
    m_str = objStringUtil.m_str;
    m_initialized = objStringUtil.m_initialized;
}

StringUtil::~StringUtil()
{
}

long StringUtil::getLength() const
{
    return (m_str.length());
}

StringUtil& StringUtil::operator=(const char* str1)
{

      string tmpStr(str1);
      m_str = tmpStr;
      return (*this);
    }
   

StringUtil& StringUtil::operator=(const StringUtil& src)
    {
        m_str = src.m_str;
        m_initialized = src.m_initialized;
   
        return *this;
    }
   
    StringUtil operator +  (const StringUtil& str1, const StringUtil& str2)
    {
        StringUtil tmpStr;
   
        tmpStr.m_str = str1.m_str + str2.m_str;
   
        return tmpStr;
    }
   
    StringUtil operator+  (const StringUtil& s1, const long int& s2)
    {
        StringUtil tmpStr;
   
        char *buf =new char[MAX_STRING_SIZE];
        sprintf(buf,"%ld",s2);
        tmpStr.m_str = s1.m_str + buf;
   
        delete buf;
   
        return tmpStr;
}

int StringUtil::extractString(int pos1, int pos2, StringUtil& result)
{
  //  Errinfo status = SUCCESS;

    const int incr1 = pos1;
    const int incr2 = pos2;

    string oldStr = (*this).m_str;
    string newStr = oldStr.substr(incr1, incr2);

    result.m_str = newStr;

    return 0;// SUCCESS;

}

int StringUtil::findAndReplace(const StringUtil& pattn, const StringUtil& repl, bool bFindOnly, StringUtil& result)
{
//    Errinfo status = SUCCESS;

//    unsigned int iPos;

    if( bFindOnly == false ) {

        int ilen = pattn.getLength();
        int iReplen = repl.getLength();
        int i = m_str.find(pattn.m_str);


        while ( i >= 0 ) {

            m_str.replace(i,ilen,repl.m_str);
            i = m_str.find(pattn.m_str,i+iReplen);

        }
    }
    result.m_str = m_str;

    return 0;// status;
   
    }
   
    int StringUtil::compare(const StringUtil& str1, const StringUtil& str2) const
    {
        if(!str1.m_str.compare(str2.m_str))
            return 1;
   
        return 0;
   
    }
   
    StringUtil StringUtil::trim()
    {
        int nPos = m_str.find_first_not_of(" ");
        if(nPos >=0) {
            m_str = m_str.substr(nPos,m_str.length());
   
            int oPos = m_str.find_last_not_of(" ");
            if(oPos>=0)
                m_str = m_str.substr(0,oPos+1);
        }
   
        return (*this) ;
   
    }
   
    StringUtil StringUtil::toUpper()
    {
        int length = (*this).getLength();
   
        for(int index=0;index<length;index++)
            m_str[index] = toupper(m_str[index]);
   
        return (*this);
    }
   
    int StringUtil::fillData(int iPos,char* cTemp)
    {
            int iStrLen = m_str.length();
   
            if (iStrLen > iPos)
            {
                m_str.replace(iPos, strlen(cTemp),cTemp);
                return 0;
            }
                    while(iStrLen < iPos)
                    {
                            m_str.insert(iStrLen," ");
                            iStrLen++;
                    }
                    m_str.insert(iPos,cTemp);
   
                    printf("After Insert Value\n");
            return 1;
    }
   
    int StringUtil::fillRepeatData(int iPos,char cTemp,int iCount)
    {
            char cTmp[3];
   
            cTmp[0] = cTemp;
        cTmp[1] = '\0';
        int iStrLen = m_str.length();
            if(iStrLen < iPos)
            {
                    while(iStrLen < iPos)
                    {
                            m_str.insert(iStrLen," ");
                            iStrLen++;
                    }
            }
            while(iStrLen < iCount+iPos)
            {
                    m_str.insert(iStrLen,(char*)cTmp);
                    iStrLen++;
            }
            return 1;
    }
   
    void StringUtil::retrieveData(int iPos, int iLen, char *pcVal)
    {
   
            m_str.copy(pcVal,iLen,iPos);
            //size_type copy(charT* buf, size_type n, size_type pos = 0) const
   
    }
   








//************** STRINGUTIL.H ********************

#ifndef STRING_UTIL_H
#define STRING_UTIL_H


#include <string>
//#include <string.h>
#include <iostream.h>
#include <list>

#define MAX_STRING_SIZE 50

class StringUtil {

public:
    StringUtil();

    StringUtil(const string&);
    StringUtil (const char* );                    // constructor

    StringUtil (const long int&);


    StringUtil(const StringUtil&);

    ~StringUtil();

    const char* getString() const;

    long int getLength () const;

    StringUtil&    operator= (const char* );            // assignment from ccharp
    StringUtil&    operator= (const StringUtil&);   // assignment from StringUtil
    StringUtil&    operator= (const long int&);   // assignment from an Int object
    bool     operator!=  (const StringUtil& s) const;


    // extracting strings given the from position(pos1) and the
    // to position(pos2)
    int extractString(int pos1, int pos2, StringUtil& result);
// find if the current object contains a certain string.
    // if the third parameter is set to true, it will only try to find if the
    // string exists
    // If the third parameter is set to false, it will find and also replace the
    // string with the replacement string
    int findAndReplace(const StringUtil& pattn, const StringUtil& repl,bool bFindOnly, StringUtil& result);

    //compares two string objects and returns TRUE or FALSE
    int compare(const StringUtil& str1, const StringUtil& str2) const;

    StringUtil toUpper() ;     // return lowercase value

    StringUtil trim();         // return string without both leading & trailing spaces

        int fillData(int iPos,char* cTemp);//similiar like the SetAt in  CString
        int fillRepeatData(int iPos,char cTemp,int iCount); // Inserts a charecter a specified number of times.
        void retrieveData(int iPos, int iLen, char *pcVal); // acts like substr


    friend StringUtil operator+  (const StringUtil& s1, const StringUtil& s2);

    friend StringUtil operator+  (const StringUtil& s1, const long int& s2);

    bool     operator<   (const StringUtil& s) const;
    bool     operator>   (const StringUtil& s) const;
    bool     operator<=  (const StringUtil& s) const;
    bool     operator>=  (const StringUtil& s) const;
    bool operator==(const StringUtil&);
    bool operator==(const char* s2);



    virtual void display (ostream& oStr) const;  // used by the << operator.

    friend ostream& operator<< ( ostream& oStr, const StringUtil& str1 )
    {
            str1.display(oStr);
            return oStr;

    }
    bool is_initialized() const;
   
    private:
   
        string m_str;
        bool m_initialized;
   
   
    };
   
    inline bool StringUtil::operator<(const StringUtil& s) const
    {
        return(m_str < s.m_str);
    }
   
    inline bool StringUtil::operator>(const StringUtil& s) const
    {
        return(m_str > s.m_str);
    }
   
    inline bool StringUtil::operator<=(const StringUtil& s) const
    {
        return(m_str <= s.m_str);
    }
   
    inline bool StringUtil::operator>=(const StringUtil& s) const
    {
        return(m_str >= s.m_str);
    }
   
    inline     bool StringUtil::operator==  (const StringUtil& str)
    {
      return(!m_str.compare(str.m_str));
    }
    inline     bool StringUtil::operator==(const char* s2)
    {
        string tmpBuffer(s2);
        return(!m_str.compare(tmpBuffer));
    }
   
inline bool StringUtil::operator!=(const StringUtil& s) const
{
 return(m_str.compare(s.m_str) != 0);
}

inline bool StringUtil::is_initialized() const
{
    return (m_initialized);
}

inline void StringUtil::display(ostream& oStr) const
{
    oStr << m_str << endl;
}

inline const char* StringUtil::getString() const
{
    return m_str.c_str();
}

#endif

What could be the problem.

Please mail me on prash_prabhu@hotmail.com.

Thank you.
0
Comment
Question by:prash_prabhu
  • 2
  • 2
7 Comments
 
LVL 12

Accepted Solution

by:
stefan73 earned 125 total points
ID: 10702505
Hi prash_prabhu,
> StringUtil::StringUtil (const long int& src)
> {
>     char *buf =new char[MAX_STRING_SIZE];
>     sprintf(buf,"%ld",src);
>     m_str = buf;
>     m_initialized = true;
>     delete buf;

> }

You can't do that, m_str will point to non-valid memory. Use instead:

StringUtil::StringUtil (const long int& src)
{
    m_str =new char[MAX_STRING_SIZE];
    sprintf(m_str,"%ld",src);
    m_initialized = true;

}

Free your buffer in the destructor. Check if you need to delete memory before assigning a new val to your buffer, like in your copy constructor StringUtil& StringUtil::operator=(const char* str1).


Cheers,
Stefan
0
 

Author Comment

by:prash_prabhu
ID: 10703039
but the same code is working in my unix environment and giving problem in itanium server
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10713284
Both using gcc?
0
 

Author Comment

by:prash_prabhu
ID: 10720753
both using aCC. I am trying to use m_str.reserver(1500) .
0
 
LVL 22

Assisted Solution

by:NovaDenizen
NovaDenizen earned 125 total points
ID: 10827420
Meta-answer:  Don't do that!  Bad Programmer! No Cookie! :-)  

Get rid of StringUtil and just use std::string!  If you want extra functionality, just write your own functions like "void assignStringFromLong(string &s, long l)".  Don't waste time trying to re-implement std::string.  IMHO it's better to adapt your ideas and your code to the well-implemented and well-designed std::string class instead of trying to wrap std::string with an unwieldy, redundant class.  Spend a nice evening with a good STL reference and read up on the use of std::string.

p.s.  It's inefficient and never necessary to pass a parameter as 'const long int& l'.  Just 'long l' will do, since it is passed by value.

p.p.s.  All uses of 'buf = new char[MAX_STRING_SIZE]; ... delete buf;' pairs can be replaced with a simple, statically allocated 'char buf[MAX_STRING_SIZE];'.  This is safer and more efficient then dynamic allocation.  It's also exception-proof.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction: The undo support, implementing a stack. Continuing from the eigth article about sudoku.   We need a mechanism to keep track of the digits entered so as to implement an undo mechanism.  This should be a ‘Last In First Out’ collec…
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now