I am experiencing a common problem with a native c++ project.
The project consists of a class and a main function file.
//LString.h - class declaration
#pragma once
class LString {
private:
char *Chars;
void Copy(const char *);
public:
int Length(void);
int IndexOf(char);
int IndexOf(const char *);
int IndexOf(LString);
int LastIndexOf(char);
int LastIndexOf(const char *);
int LastIndexOf(LString);
void Replace(char,char);
void Replace(LString,LString);
void Remove(int Index, int Count);
LString SubString(int Index);
LString SubString(int Index, int Count);
public:
char& operator [] (int Index);
LString& operator = (const LString &);
LString& operator = (const char *);
public:
LString(const LString &);
LString(void);
~LString(void);
};
//LString.cpp - class implementation
LString::LString(void) {
Chars = new char[1];
*Chars = 0;
}
void LString::Copy(const char *s) {
int slen = 0;
int i = 0;
for (i=0 ; *(s+i)!=0 ; i++);
slen = i;
delete [] Chars;
Chars = new char[slen+1];
for (i=0 ; i<=slen ; i++) {
*(Chars+i) = *(s+i);
}
}
LString::LString(const LString &s) {
Copy(s.Chars);
}
LString::~LString(void) {
delete [] Chars;
}
void LString::Replace(LString s, LString p) {
while (IndexOf(s)>0) {
char *Temp = new char[Length()+s.Length()-p.Length()];
int i = 0 ;
for (i=0 ; i<IndexOf(s) ; i++) {
*(Temp+i) = *(Chars+i);
}
for (i=0 ; i<p.Length() ; i++) {
*(Temp+IndexOf(s)+i) = p[i];
}
for (i=IndexOf(s)+s.Length() ; i<Length() ; i++) {
*(Temp+p.Length()-s.Length()+i) = *(Chars+i);
}
*(Temp+i) = 0;
Copy(Temp);
delete [] Temp;
}
}
int LString::IndexOf(const char *c) {
char *cp = Chars;
char *s1, *s2;
if ( !(*c) ) {
return 0;
}
while (*cp) {
s1 = cp;
s2 = (char *) c;
while ( *s1 && *s2 && !(*s1-*s2) ) {
s1++, s2++;
}
if (!*s2) {
return (int)(cp-Chars);
}
cp++;
}
return -1;
}
int LString::IndexOf(LString s) {
return IndexOf(s.Chars);
}
int LString::Length(void) {
for (int i=0 ; ; i++) {
if (*(Chars+i)==0) {
return i;
}
}
}
LString& LString::operator = (const LString &s) {
Copy(s.Chars);
return *this;
}
LString& LString::operator = (const char *s) {
Copy(s);
return *this;
}
LString will try to dynamically allocate memory according to the length of the char * that has to be copied by deleting the older pointer and allocating a new one (Copy method). The copy constructor and assignement operator has to do almost the same job. I didn't include the implementation of the other methods as they are not triggered by the main function thus their importance is lesser.
The following main function will generate a heap corruption:
#include "LString.h"
int _tmain(int argc, _TCHAR* argv[])
{
LString MyString;
LString String1; LString String2; String1 = "l"; String2 = "t";
MyString = "oll";
MyString.Replace(String1,String2);
return 0;
}
What am I doing wrong Any ideas
Thanks for reading.