I'm working on a string class in C++ using the C standard library.
The class is fairly simple: The constructor takes a string and allocates the amount of memory required for it into a char pointers using malloc, the constructor frees it, and if required, it reallocs. The rest is reading/writing functions that don't require more or less memory.
One function I made changes the contents to lower case, puts it in a new object (created on the stack) and returns it. However, I tried doing something along the lines of: str = str.toLower(); and needless to say, it failed horribly.
Every other time I launch the exe it crashes. After hours after mindlessly searching, I made message boxes tell me when something is allocated and freed and what it is. Turns out for some reason, it kept allocating and deallocating various items from where ever. I'm assuming it was due to a dangling pointer, so I fixed that.
However, it's still allocating and freeing a bunch of things and crashing.
Here is the relevant code:
Constructor/Destructor:
String::String(const char* str)
{
data = nullptr;
MessageBox(NULL, str, "Allocating", MB_OK);
//getSizeOfCharArray does not include the NULL at the end, so add 1
data_size = getSizeOfCharArray(str)+1;
data = (char*)malloc(sizeof(char)*data_size);
strcpy(data, str);
}
String::~String()
{
MessageBox(NULL, data, "Freeing", MB_OK);
if (data != nullptr)
{
free(data);
data = nullptr;
}
}
Lowercase function:
String String::toLower()
{
char* lower = (char*)malloc(sizeof(char)*data_size);
for (int i = 0; i < data_size; i++)
{
lower[i] = tolower(data[i]);
}
String temp(lower);
free(lower);
return temp;
}
Main:
int main()
{
String str("String contents");
str = str.toLower(); /* This line is what causes everything
to go wrong. But why? */
cout << str.c_str() << endl; //c_str returns a const char* pointer
//Alternatively, I can do this and it's fine.
cout << str.toLower().c_str() << endl;
}
The boxes go as follows:
Allocating "String contents"
Allocating "string contents"
Freeing "string contents"
Allocating "/z" (actually some other character that looks like z)
Freeing "/z" (same strange character)
Allocating "/z" (same)
Freeing "/z" (they're all not z)
Allocating "/z"
Freeing "/z"
Allocating "/z"
Freeing "/z"
Allocating "/z"
Freeing "/z"
Allocating "/z"
Freeing "/z"
Allocating "/z"
Freeing "/z"
I have got other dialog text, but apparently "/z" is a common one.
It goes on like this for a bit.
What could be possibly causing this?