My assignment is to make a program that can resize a dynamically allocated array. But when I delete a value, the program crashes (memory leak?). Here's my code.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <limits>
using namespace std;
typedef char* charPtr;
typedef charPtr* strPtr;
strPtr delEntry(strPtr a, int &size, charPtr str);
charPtr getStr();
void printMenu();
char getch();
void resize(strPtr &a, int &size, int new_size);
void delStr(strPtr a, int pos, int size);
int search(strPtr a, int size, charPtr str);
int main() {
strPtr a;
char ch;
charPtr str;
int size = 5;
a = new charPtr[size];
str = new char[80];
for (int i = 0; i < size; i++)
a[i] = new char[80];
cout << "Enter five names." << endl;
for (int i = 0; i < size; i++)
a[i] = getStr();
cout << endl << "------------" << endl << endl;
printMenu();
cout << endl;
ch = getch();
while (ch != '4') {
switch (ch) {
case '1':
cout << endl << "Enter string to add." << endl;
str = getStr();
resize(a, size, size + 1);
a[size - 1] = str;
break;
case '2':
cout << endl << "Enter string to delete." << endl;
str = getStr();
delEntry(a, size, str);
break;
case '3':
cout << endl;
for (int i = 0; i < size; i++)
cout << a[i] << endl;
case '4':
break;
default:
cout << endl << "Invalid choice.";
}
cout << endl << "-------------------" << endl;
printMenu();
ch = getch();
}
}
charPtr getStr() {
charPtr str;
str = new char[80];
cout << ": ";
cin >> str;
return str;
}
void printMenu() {
cout << "[1] Add entry." << endl << "[2] Delete entry." << endl <<
"[3] List array." << endl << "[4] Exit." << endl << "Choice: ";
}
char getch() {
char ch;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //Flush
ch = cin.get();
return ch;
}
strPtr delEntry(strPtr a, int &size, charPtr str) {
int index = -1;
resize(a, size, size - 1);
if (index == -1) return a;
delStr(a, index, size);
return a;
}
void resize(strPtr &a, int &size, int new_size) {
strPtr b;
b = new charPtr[new_size];
for (int i = 0; i < new_size; i++)
b[i] = new char[80];
for (int i = 0; i < size; i++)
strcpy(b[i], a[i]);
delete [] a;
a = b;
size = new_size;
}
void delStr(strPtr a, int pos, int size) {
for (int i = pos; i < size; i++)
a[i] = a[i + 1];
}
int search(strPtr a, int size, charPtr str) {
for (int i = 0; i < size; i++)
if (strcmp(a[i], str) == 0) return i;
}