Resizing Dynamic Arrays Without MemLeaks

I am using the following code to test how to properly resize arrays.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main() {
	int* c = new int[10];
	
	for(int i = 0; i < 10; i++)
	{
		c[i] = (3*i)/2;
		cout << c[i] << " ";
	}
	cout << endl;
	
	c = new int[20];
	
	for(int i = 0; i < 20; i++)
	{
		c[i] = i;
		cout << c[i] << " ";
	}
	cout << endl;
	return 0;
}


It works as expected, but one questions remains. Will this code cause a memory leak? If so, what do I do to plug the leak?
Yes, you have a memory leak.

Line 14: you reallocate c without releasing the old c.

1
2
3
//  Line 13:
 delete c[];
    delete [] c;


You should also release c at the end of the program.
Last edited on
I initially did that before reallocating in a program and I got a segfault.
@AbstractionAnon: the syntax is: delete[] c;

@Sh0es: yes your programm has a memory leak as AbstractionAnon described.
Furthermore it would have a memory leak at the end as well but whenever the process exits all space allocated by the process gets delocated

Here is the running code(only added that line of code): http://cpp.sh/4iii
Oops. Corrected.
Topic archived. No new replies allowed.