Should I call the delete function here?

This is my program, should I call the delete function for
delete_repeats(a, size) in order to return the memory for freestore.
*** delete [] delete_repeats(a, size); ***
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream> // library for cin/cout

typedef char* charArrayPtr;
using namespace std;

char* delete_repeats (char a[], int& size);
//Precondition:
//Postcondition:


int main() {
    using namespace std;
    char a[10] = {'a', 'b', 'a', 'c', 'b', 'd', 'e', 'c', 'e', 'a'};
    int size = 10;
    cout << "The array of size " << size << " before deleting repeated contains:\n";
    for (int i = 0; i < size; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
    charArrayPtr array = delete_repeats(a, size);
    cout << "The new size of the array after deleting repeated is: " << size << endl;
    for (int i = 0; i < size; i++) {
        cout << *(array + i)<< " ";
    }
    cout << endl;
    delete [] array;
    delete [] delete_repeats(a, size);
    return 0;
}
char* delete_repeats (char a[], int& size) {
    int k(1), l;
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (a[i] == a[j]) {
                l = j;
                while (k < (size - j)) {
                    a[l] = a[l+1];
                    l++;
                    k++;
                }
                size--;
            }
        }
    }
    charArrayPtr array = new char[size];
    array = a;
    return array;
}

/*
 Sample Dialogue:
 
 The array of size 10 before deleting repeated contains:
 a b a c b d e c e a
 The new size of the array after deleting repeated is: 6
 a b c b d e
 
 */
You should use delete with everything that was allocated with new.

Note that your delete_repeats function returns the a array that was passed to the function.

1
2
3
4
5
6
7
8
9
10
// array points to the (first element of the) new array.
charArrayPtr array = new char[size]; 

// array points to the same location as a. 
// This causes a memory leak because you no longer have pointer to 
// the new array, so there is no way you can delete it.
array = a;

// array and a points to the same location so this is the same as having return a;
return array;

Last edited on
Thanks @Peter87
Topic archived. No new replies allowed.