• 0

C++ MyString Class


Question

I would just like someone to check this function, because I'm not sure if I did it completely right. I have a MyString class with size, capacity, and data member variables. size is like strlen. capacity is size + 1 (for the null terminator) and data is a char array.

In this code, do I need to check for null arrays? I'm not quite sure how to do this.

I'm creating a MyString instance to hold str + this->data and then I return it. I think it's a little sloppy and could maybe be implemented better. Any suggestions? Thanks!

// in testString.cpp

MyString s1;

s1 = s2 + cString; // s2 contains "hi" and cString contains "world"

// s1 should now be... "hiworld"

MyString MyString::operator + (const char* str)
{
	MyString concatStr;

	concatStr.size = this->size + strlen(str);
	concatStr.capacity = concatStr.size + 1;
	concatStr.data = new char[concatStr.capacity];

   // copies the first string
	for (int i = 0; i < this->size; i++) 
       concatStr.data[i] = this->data[i];

	// copies the second string
	for (int i = 0; i < strlen(str)+1; i++)   // plus one for the /0
        concatStr.data[i+(this->size)] = str[i];  
  
	return concatStr;	
}

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

capacity shouldnt be strlen + 1. it should be a size that is a multiple 2.

What some string libs do, is when you concatenate/modify/do any op on a string, if it needs to allocate any memory, it allocates more than it needs. that way if you add some more data that will fit within the extra room, you dont have to copy memory over and allocate new memory.

That's my only recommendation.

Link to comment
Share on other sites

  • 0
How does strlen have the potential for buffer overflow? It just returns the length of the string? Never heard of strzlen, either.

Sorry about that... strnlen... not strzlen. strzlen was a custom class I wrote once before strnlen.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.