where should i release the dynamic memory?

i allocated dynamic memory in the function's... where should i "free" the memory?
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <iostream>
#include <stdlib.h>

using namespace std;

int* merge(int *a1, int n1, int *a2, int n2)
{
	int i = 0, j = 0, k = 0;
	int size = n1 + n2;
	cout << "Merged Array: ";

	if (size == 0)
	{
		cout << "EMPTY ARRAY" << endl;
		return NULL;
	}

	int* arr = (int *)malloc(size*sizeof(int));

	while (i < n1 && j < n2) 
	{
		if (a1[i] <= a2[j])
		{
			arr[k] = a1[i];
			i++;
			k++;
		}
		else 
		{
			arr[k] = a2[j];
			j++;
			k++;
		}
	}

	while (i < n1)
	{
		arr[k] = a1[i];
		i++;
		k++;
	}
	while (j < n2)
	{
		arr[k] = a2[j];
		j++;
		k++;
	}
	return arr;
}

int find_index(int a[], int size, int value)
{
	int i;
	for (i = 0; i<size; i++)
	{
		if (a[i] == value)
		{
			return(value);  
		}
	}
	return(-1);  
}

int* merge_uniq(int *a1, int n1, int *a2, int n2,int* len)
{
	int i = 0, j = 0, k = 0;
	int size = n1 + n2;
	cout << "Uniq Merged Array: ";


	if (size == 0)
	{
		cout << "EMPTY ARRAY" << endl;
		return NULL;
	}

	int* arr = (int *)malloc(size*sizeof(int));

	while (i < n1 && j < n2) {
		if (find_index(arr, size, a1[i]) != -1)
			i++;
		else if (find_index(arr, size, a2[j]) != -1)
			j++;

		else if (a1[i] <= a2[j])
		{
			arr[k] = a1[i];
			i++;
			k++;
		}
		else
		{
			arr[k] = a2[j];
			j++;
			k++;
		}
	}

	while (i < n1)
	{
		arr[k] = a1[i];
		i++;
		k++;
	}

	while (j < n2) 
	{
		arr[k] = a2[j];
		j++;
		k++;
	}

	return arr;
}

void display(int* arr,int size)
{
	for (int i = 0; i < size; i++)
		cout << arr[i];
	cout << endl;
}

int main()
{
	int arr1[] = { NULL };
	int arr2[] = { NULL };
	int* Marr, *MUarr;
	Marr = merge(arr1, 0, arr2, 0);
	MUarr = merge_uniq(arr1, 0, arr2, 0,arr1);
	display(Marr, 11);
	display(MUarr, 10);
	
}

After you done with it. In your code that means at the end of main().
malloc ← Why? Use new[] in C++. Also you might use unique_ptr to automaticly manage your memory without you worrying about it.
Topic archived. No new replies allowed.