-
Debug failure error
I'm trying to create my own string class, which I named CStr.
First, I defined it as such (I left out a lot of irrelevant code at the moment):
Code:
class CStr
{
char* pData;
int nLength;
int stlen(char* c){for(int i = 0; *c != '\0'; c++, i++); return i;}
char* stcpy(char*, const char*);
char* stcat(char*, const char*);
public:
CStr(char*);
void set(char* c){stcpy(pData, c);}
};
Then the member function definitions:
Code:
char* CStr::stcpy(char* dest, const char* src)
{
char* p;
p = dest;
if(nLength > 0)
{
delete [] pData;
pData = new char[stlen(src)];
p = dest = pData;
}
while(*(p++)=*(src++));
return dest;
}
CStr::CStr(char* c)
{
pData = new char[stlen(c)];
stcpy(pData, c);
nLength = stlen(c);
}
Now here's the code from the main() function.
Code:
char* p = "First input";
char q[256];
CStr c(p);
while(gets(q))
c.set(q);
My problem is that I get a "Debug Error" message (in VC++ 2003)) which states as follows:
DAMAGE: After Normal Block(#42) at XXXXX.
This occurs at the line "delete [] pData" in the definition of stcpy() when it is called by "c.set(q)".
Please tell me, what am I doing wrong here?
-
you don't allow room for the null-terminator
Code:
pData = new char[stlen(src)+1];
why does strcpy() method have two parameters? It only needs one -- the source string. Destination string should always be pData, which does not have to be passed to the function.
-
Thanks, your correction worked perfectly.
As for my stcpy function, I was curious how the actual strcpy function in string.h worked so I thought I might as well try my hand at mimicing it. I could have written one specifically for this class, but just wanted to make something generic.
-
Hi,
The defining aspect of a C-style string is that it ends in a '\0' character. However, that '\0' is not included in the strlen() count. That will constantly trip you up when dealing with C-style strings. The '\0' is required at the end of C-style strings because it indicates to all the <cstring> functions where the characters in the array end. There's no bounds checking in C++, so a while loop will go right past the end of an array and into uncharted memory if you let it. cout<< also uses that '\0' to determine when to stop outputing characters to the screen. So, don't forget about the '\0'!
Your strcat() function will provide a little twist on that concept because you don't want to end up with:
"string1\0string2\0"
The <cstring> functions and cout<< use a while loop to advance along the array one character at a time, and the loop will terminate when a '\0' character is encountered. So those functions won't be able to see anything past the first '\0'.