CPSC 259 Chapter Notes - Chapter 7.1: Local Variable, Ampersand

17 views2 pages
6 Aug 2016
School
Course
The basic advantages of local variables are that they are convenient as functions
often need a temporary storage area that is independent from all the other
memory storage. So the concept behind local storage allows function to do so.
The other advantage is that allocating and deallocating memory to the variables
is quite fast, hence this speeds up the processing speed of a compiler.
Another advantage is that the parameters are passed by reference, so each
function gets a copy of the parameter. What that does is that allows the function
to change the parameter without worrying about its effect on other functions.
However, the obvious downside is that it hinders communication between
different functions.
Another disadvantage is that this can lead to the ugly run time errors. This
happens because the local variables life time is fixed and the variables used by
one function are automatically deallocated once it is used, so if these variables
are passed to another function, then this can create problems.
The ampersand bug
A good demonstration of disadvantage number 2 happens in the ampersand bug,
where essentially you define a function, that has a return type of a pointer. During
the function, you assign a variable to the pointer and you return this pointer to
another function. During the operation of the second function you use the pointer to
allocate a value to another variable. Here you run into a run time error. In the first
function, the use of the variable as the pointee was alright, but once you ended the
original function, you passed the pointer which was alright, but its pointee vanished,
as it was a local variable of the initial function, hence you assigned a deallocated
variable to the pointer and when you used the pointer to assign a value to a different
variable, you got run time error owing to the limited run time of local variables.
Here is a corresponding code:
Int* A() {
Int b;
Return (&b) // here you are returning the pointer }
Void c() {
Int d;
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Get access

\$10 USD/m
Billed \$120 USD annually
Homework Help
Class Notes
Textbook Notes