These lines of code are giving me the error: free() double free detected in tcache 2 when I attempt to run the program. If i remove the final line, there is no error. append_new is a method that searches the array within item_vec and adds "initialString" to the end of the array. The method append_new has been tested in other programs. Could someone please explain the reason for this error and how to fix?
class item_vec {
// Create private set of variables
private:
int strSize;
int strCapacity;
string* arr;
// Define functions in public
public:
item_vec()
: strSize(0), strCapacity(10)
{
arr = new string[strCapacity];
}
item_vec(int n, string s)
: strSize(n), strCapacity(2 * n + 1) // initializer list
{
// Check for out of bounds error
if (n < 0) {
cmpt::error("str_vec(int n, string s): n must be 0 or greater");
}
// make array and populate with string s
arr = new string[strCapacity];
for (int i = 0; i < strSize; i++) {
arr[i] = s;
}
}
int size() const {
return strSize;
}
void append_new(string s) {
// Variable to track if string is already present
bool hasString = false;
// Iterate through and update if string found
for (int i = 0; i < strSize; i++) {
if (arr[i] == s) {
hasString = true;
}
}
// If string isnt found append to end
if (hasString == false) {
// Make new copy array and replace old if no space
if (strSize >= strCapacity) {
strCapacity *= 2;
string* new_arr = new string[strCapacity];
for (int i = 0; i < strSize; i++) {
new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;
delete[] new_arr;
}
// Update array
arr[strSize] = s;
strSize++;
}
}
// Make destructor
~item_vec() {
delete[] arr;
}
};