Dynamic Memory Allocation

This is a discussion on Dynamic Memory Allocation within the C++ Programming forums, part of the General Programming Boards category; Hi all, I need to design and implement a String class for the given code, and this class should store ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    8

    Dynamic Memory Allocation

    Hi all,

    I need to design and implement a String class for the given code, and this class should store the string in a dynamically allocated memory.

    Code:
    int main()
    {
           String s1, s2 = "Done!";
           X = "Well " + s2;
           cout << s1 << endl;
           return 0;
    }
    I'm getting confused in overloading "+" operator. Here's my work...

    Code:
    class String
    {
     private:
             enum { size = 80 };         
             char str[SZ];
     public:
            String()
            {
                str[0] = '\0';
            }
            
            String(char s[])
            {
                strcpy(str, s);
            }
    
            String operator + (String s1) const
            {
                String a;
                   strcpy(a.str, str);
                   strcat(a.str, s1.str);
                   return a;
            }
    };
    Any help please?

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,412
    operator+() is clearly the problem since you are incurring in a buffer overflow both on strcpy() and strcat() calls. You should read more about these two functions. It's important you use them correctly since they are some of the biggest contenders for bugs both in C and C++. strncpy and strncat are somewhat safer, but not too much really...

    Anyways,

    My first advise to you is to immediately define a length() member function that returns the size of the str data member array. I believe it should return the size of the array minus the null element. In order to do this, a quick way is to simply iteratate through str until you find the null terminator.

    This member function will be your life savior. You will be using it everywhere. It tells you the size of String without the null character. Defining operator+() with strncpy() and strncat() will then become much, much easier.

    The second thing you must make sure is that your parameterized constructor should check for the existence of a null terminator and add one to the end of str in case it doesn't exist. As is right now, your String(char s[]) constructor can construct the str data member without a null terminator. That would foil your length() function member... and the whole of your class.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,412
    On a second note, I'm very limited on the type of help I can provide here. I believe the above are right choices that will help you tremendously to simplify the rest of your class construction. But wrapping a c style string is no trivial task... Your teacher was not kind at all. To that I add the fact, I'm not really that comfortable with c strings anyways.

    One of the problems you will face is exactly with my second advise. How do you really check for the presence of a null terminator? The problem here is that the char array is passed without a size. You simply don't know the size of the array, so you could end up looking outside its bounds. I don't think making it String(const char* s) will be enough. Since it is still possible to pass a non null terminated char array to it.

    Someone else may provide an answer to this.

    EDIT: One solution is to go ahead and place '\0' at the end of the string anyways. That's kind of hackish but quiet safe. No matter what your str will always hold a null terminated string. Of course, if the string passed to the constructor already contains one, you will be wasting 8 bits of memory. A small price to pay, I guess.

    Also, I was looking at your class again... you cannot expect to do this with fixed size arrays. You have to use dynamic ones. Come to think of it, that was probably the original intent of your thread. go here for an introduction http://www.cprogramming.com/tutorial/lesson9.html and check google for "c++ c-style strings" or something similar.
    Last edited by Mario F.; 11-28-2006 at 05:36 AM.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,414
    Since you intend to use dynamic memory allocation, I suggest that you have a char* member variable to store the string content, and two unsigned int (or std::size_t) member variables for size and capacity.

    Make operator+ a free function, and implement it in terms of a member function operator+=, e.g.
    Code:
    String operator+(const String& a, const String& b) {
        return String(a) += b;
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Replies: 16
    Last Post: 01-01-2008, 03:07 PM
  3. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  4. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21