So I am really frustrated as to why this is happening. I am implementing a class that is similar to std::string but this is using Link List instead of arrays. my overloaded operator = is not working for some odd reason. below you can see, when I print the pointer inside the method the string is copied to the link list, however when I create a string object with this pointer to return, then the console prints out infinite junk. any ideas to what I am missing here ? (I am only pasting related code)
static int NumAllocations = 0;
struct ListNode {
char info;
ListNode *next;
ListNode () : info('0'), next(0) {}
ListNode ( char c ) : info (c), next(0) {}
};
class MyString {
private:
ListNode *head;
static void delstring (ListNode *l);
static int strlen (ListNode * head);
static ListNode* strcpy (ListNode *dest, ListNode *src);
public:
MyString::MyString () : head(0) {}
MyString::MyString (ListNode *l) : head(l) {}
MyString::MyString( const MyString & s ) {
if (s.head == 0)
head = 0;
else
head = strcpy(head, s.head);
}
MyString MyString::operator = (const MyString & s ){
ListNode *renew = NULL;
if (head != s.head) {
if (head != 0)
delstring(this -> head);
head = strcpy(head, s.head);
// printList(head); (this prints out the string just fine, so it must be the constructor ? but what about it ?!
MyString res (head);
return res;
}
}
MyString::~MyString(){
if (head == 0)
return;
ListNode *temp = NULL;
do {
temp = head -> next;
delete head;
-- NumAllocations;
head = temp;
} while (temp != 0);
}
STATIC PUBLIC FUNCTIONS
ListNode* MyString::strcpy (ListNode *dest, ListNode *src){
dest = new ListNode (src -> info);
++ NumAllocations;
ListNode *iter = dest;
for (ListNode *ptr = src -> next; ptr != 0; ptr = ptr ->next){
iter -> next = new ListNode (ptr -> info);
iter = iter -> next;
++ NumAllocations;
}
return dest;
}
void MyString::delstring (ListNode *l){
if (l == 0)
return;
ListNode *temp = NULL;
do {
temp = l -> next;
delete []l;
-- NumAllocations;
l = temp;
} while (temp != 0);
l = 0;
}
destis even supplied to the poorly namedstrcpymember. It is passed by value, and whatever it was is immediately lost on the first line, so it may as well be a local variable and not a parameter at all. That function looks like it may be a problem, so I'd start there.