Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 7 - Back to Basics: Memory<br />
When we exit our main function (forget the fact that the program will stop), our stack pops <strong>of</strong>f all local<br />
values, meaning both the x and y values are lost. This is significant because the memory allocated on the<br />
heap still contains our string, but we've lost all references to it (there's no pointer pointing back to it). In<br />
C or C++ this results in a memory leak - without a reference to our heap address we can't free up the<br />
memory. In C# or Java, our trusty garbage collector will detect the unreferenced object and free it up.<br />
We'll look at a more complex examples, but aside from having more arrows, it's basically the same.<br />
public class Employee<br />
{<br />
private int _employeeId;<br />
private Employee _manager;<br />
public int EmployeeId<br />
{<br />
get { return _employeeId; }<br />
set { _employeeId = value; }<br />
}<br />
public Employee Manager<br />
{<br />
get { return _manager; }<br />
set { _manager = value; }<br />
}<br />
public Employee(int employeeId)<br />
{<br />
_employeeId = employeeId;<br />
}<br />
}<br />
public class Test<br />
{<br />
private Employee _subordinate;<br />
}<br />
void DoSomething()<br />
{<br />
Employee boss = new Employee(1);<br />
_subordinate = new Employee(2);<br />
_subordinate.Manager = _boss;<br />
}<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
56