Memory leaks and pointers

closed account (G1vDizwU)
Hello guys,

Regarding to an exercise I wrote the code below. The program runs well but I have two questions about it:

1- Is there any memory leak in the program I've forgot to release?

2- Why do I need to use static for the array in double* get_from_jack(int* count) function but not for vector<double>* arr in vector<double>* get_from_jill() please?


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
#include <std_lib_facilities_4.h>
using namespace std;

//**************************************************

template<class Iterator >
Iterator high(Iterator first, Iterator last)
// return an iterator to the element in [first:last) that has the highest value
{
	Iterator high = first;
	for (Iterator p = first; p != last; ++p)
		if (*p > *high)
			high = p;
	return high;
}

//*********************************************************************

double* get_from_jack(int* count);  // jack puts doubles into an array
									// and returns the number of elements
									// in *count
vector<double>* get_from_jill();    // Jill fills the vector

//*******************************************************************

void fct()
{
	int jack_count = 0;

	double* jack_data = get_from_jack(&jack_count);
	vector<double>* jill_data = get_from_jill();

	double* jack_high = high(jack_data, jack_data + jack_count);

	vector<double>& v = *jill_data;
	double* jill_high = high(&v[0], &v[0] + v.size());

	cout << "Jill's high " << *jill_high << ";  Jack's high " << *jack_high << endl;
}

//*****************************************************************************************

int main()
{
	try
	{
		fct();
	}
	catch (exception& e)
	{
		cout << "Standard exception: " << e.what() << endl;
	}
	catch (...)
	{
		cout << "Unknown exception" << endl;
	}
	system("pause");
	return 0;
}


//**********************************************************

double* get_from_jack(int* count)
{
	int i = 0;
	double d;
	static double arr[100];

	ifstream f1_read;
	f1_read.open("num1.txt");

	if (f1_read.is_open())
		while (!f1_read.eof()) {
			f1_read >> d;
			arr[i++] = d;
		}

	*count = i;
	f1_read.close();

	return arr;
}

//**********************************************

vector<double>* get_from_jill()
{
	vector<double>* arr = new vector<double>;
	double d;

	ifstream f2_read;
	f2_read.open("num2.txt");

	if (f2_read.is_open())
		while (!f2_read.eof()) {
			f2_read >> d;
			arr->push_back(d);
		}

	f2_read.close();

	return arr;
}


Last edited on
You allocate an object using new, and you never delete it. This becomes a leak when you lose the pointer to it.

What we're seeing here is two different ways to make an object exist beyond the scope of the function in which it is created. static memory is allocated before main begins, and the array you've declared static will exist throughout the programme run.

Use of new is another attempt to get an object to exist beyond the scope of the function in which it is created. The object will continue to exist until you delete it.

In both cases, there are better ways to do this that static or new, but if this is just a learning exercise to understand how these work, fine.
closed account (G1vDizwU)

I added delete jill_data; at the end of fct(). Is it OK now please?

Do you mean if we create a pointer using new, it remains even out of its scope?

And is it correct that arrays don't remain out of scope and we should make them static to use in out of scope?
Do you mean if we create a pointer using new, it remains even out of its scope?

When you allocate memory dynamically (i.e. using new), that memory remains allocated until you delete it, using the delete keyword.

To access that memory, you need to store its address in a pointer variable. As long as you have that value, you can access the memory. The scoping rules for that pointer variable are the same as the rules for any other variable.

Note that, if the pointer variable drops out of scope, that doesn't mean the memory gets freed up; it remains allocated unless you manually delete it. We call this a memory leak, because it causes your program to use up memory that never gets freed (until the program exits), meaning that memory can't be re-used.

In modern C++, we get around this problem by using smart pointers, which are template classes that wrap a pointer, and which automatically free up memory at the appropriate point.

And is it correct that arrays don't remain out of scope and we should make them static to use in out of scope?

Arrays have the same scoping rules as any other variables. If you create a local variable (be it an array, or any other kind of variable), then when it goes out of scope, the memory is reclaimed by the program and can be used to store other data.

The issue here is that, when you return an array, what you're actually returning is a pointer to the memory storing that array. If the array is local, then once it's out of scope, the pointer is pointing to memory that has been reclaimed and could have been used for something else; you can no longer rely on it containing the values you stored in it when it was being used for the array.

A static variable persists after the function has exited, so that the next time the function is called, it still holds the value it held at the end of the previous call. A side-effect of this is that the pointer you're returning to the function points to memory that still holds the values you want to access.

As Moschops says, it's not the best way to achieve what you're trying to do, but it works, and hopefully will help you understand how these language features work.
Last edited on
Topic archived. No new replies allowed.