C++ Scope and the Heap

Creator:
bfr
Description:
This tutorial will try to teach beginners about scope and the heap.

C++ Scope Tutorial

Definition
The scope of a variale is the rande of which it is defined.

Example
For example, a variable declared within a function is only accessible within it. A variable declared outside of a function is accessible anywhere though. Consider the following code snippet:

// Exists throughout the program double
globalVariable;
void myFunction(void){
// Exists only in this function double variableA;
}
int main(void){
myFunction();
}

The snippet starts off by execueint the function "main". Then, it runs myFunction. myFunction declates the variable variableA. When myFunction exits, the variable previously declared, variableA, is no longer accessible and in fact, no longer even exists (it goes out of scope). The part of memory that it is at is probably now being used by something else. A variable out of scope can't even be returned by a function.

Using the Heap

A block of memory under complete control of the programmer is often known as the "heap". The scope problem can be solved by useing the "new" keyword to allocate memory off the heap. The following code snippet should help demonstrate this:

// This does not work
int* aFunction(void){
int localVariable;
return &localvariable;
}
void anotherFunction(void){
int* pointerLocalVariable;
pointerLocalVariable = aFunction();
*pointerLocalVariable = 34;
}

// This does work
int* aFunction(void){
// Allocate a memory off the heap
int* pointerLocalVariable = new int;
return pointerLocalVariable;
}
anotherFunction(void){
// aFunction returns the address of
// the block of heap memory allocated
int* differentVariable = aFunction();
// Store 34 in the address of allocated
// memory
*differentVariable = 34;
// Memory returned to heap by using "delete"
delete pointerLocalVariable;

As you can see in the above code, the "new" keyword is used to allocate some memory off the heap. To clarify things, the following shows how to allocate some memory off the heap: type* variable name = new type You may also notice the "delete" command. This returns the memory back to the heap. You use "delete" with the pointer variable used when allocating the memory.

All in all...

I could go into all the details and could expand the length of this tutorial, but it's already long enough. Also, excuses my long variable names - they are used to clarify if they are local or not, etc. Well, you all now have (or at least I hope so) a fairly good understanding of allocating memory off the heap, and what scope means and what the heap is. Happy coding =)

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <u> <i> <hr> <img src <url=
  • Lines and paragraphs break automatically.

More information about formatting options