pointers; fix heap corruption

This commit is contained in:
2024-05-24 17:45:06 +03:00
parent 0acc416efd
commit 1d3df752ff

36
pr4.cpp
View File

@@ -16,6 +16,7 @@ public:
capacity = Capacity;
p = new char[capacity];
len = 0;
p[0] = '\0'; // Initialize with an empty string
}
explicit BaseString(const char* ptr) //create object from input string
@@ -23,8 +24,7 @@ public:
{
cout << "\nBase Constructor 1\n";
len = Length(ptr);
capacity = len; // allocate needed memory dynamically based on the Length of the input.
//avoid unnecessary memory allocation.
capacity = len + 1; // allocate needed memory dynamically based on the Length of the input including null terminator
p = new char[capacity];
CopyString(p, ptr, len);
}
@@ -53,7 +53,7 @@ public:
{
*destination++ = *source++;
}
*destination = '\0';
*destination = '\0'; // Ensure the destination is null-terminated
}
int Length() const { return len; }
@@ -80,16 +80,18 @@ public:
{
cout << "\nBase Copy Constructor\n";
len = s.Length();
p = new char[s.capacity];
capacity = s.capacity;
p = new char[capacity];
CopyString(p, s.p, len);
}
virtual void print() const
{
for (int i = 0; i < len; i++)
const char* ptr = p;
while (*ptr != '\0')
{
cout << p[i];
cout << *ptr;
ptr++;
}
}
@@ -132,24 +134,26 @@ public:
int LastIndexOf(const char* substr) const
{
int substrLen = BaseString::Length(substr);
int startPos = len; // Start searching from the end of the string
while (startPos >= 0)
if (substrLen > len) return -1; // substr longer than the string
const char* start = p + len - substrLen; // Start from the last possible position
while (start >= p)
{
int i = 0;
while (i < substrLen && p[startPos + i] == substr[i])
const char* current = start;
const char* sub = substr;
while (*sub != '\0' && *current == *sub)
{
i++;
current++;
sub++;
}
if (i == substrLen) // If the entire substring matches
if (*sub == '\0') // If the entire substring matches
{
return startPos;
return start - p;
}
startPos--; // Move to the previous position
start--;
}
return -1; // Not found
}
};
int main() {