SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
Lecture 3: Variables and Storage




                      TI1220 2012-2013
              Concepts of Programming Languages

                       Eelco Visser / TU Delft
Outline
  Messages from the lab
  Variables & storage
  Copy & reference semantics
  Lifetime
  Local & heap memory
  Memory management
  (Memory and pointers in C)
Messages from the Lab
full discussion next week
New release of WebLab

New release of WebLab
Re-enroll to participate for credit
Deadline: final date that assignment
      can be submitted without penalty




Due date (new): advise date for finishing
assignment to help you plan your work
Variables & Storage
A program variable is an abstraction of a
computer memory cell or collection of cells
Von Neumann Architecture: stored-program computer in
which an instruction fetch and a data operation cannot occur
    at the same time because they share a common bus




           http://en.wikipedia.org/wiki/File:Computer_system_bus.svg
Chapter 3: Variables
   and Storage
Storage Cell
   unique address
   status: allocated or unallocated
   content: storable value or undefined


primitive variable        63

                         ‘foo’
composite variable         ?      undefined
                         false

 unallocated cell
storable value: can be
            stored in single storage cell



C++: primitive values and pointers


        Java: primitive values and pointers to objects



    Typically: composite values are not storable
simple variable: a variable that may contain a
    storable value; occupies a single storage cell




                 {
                                                            ?
                     int n;
          C          n = 0;                                 0
                     n = n + 1;
                                                            1
                 }



terminology: “the content of the storage cell denoted by n” ~ “the value of n”
dates
composite variable: a variable
 of a composite type, occupies a     dates[0]   y   2013
    group of contiguous cells
                                                m       1
                                                d    31
struct Date {
                                     dates[1]   y   2013
  int y, m, d;
}                       C
struct Date today;                              m       2
today.m = 2;
today.d = 26;                                   d    26
today.y = 2013;         today        dates[2]   y       ?
struct Date dates[3];   y   2013                m       ?
dates[0].y = 2013;
dates[0].m = 1;         m       2               d       ?
dates[0].d = 31;
dates[1] = today;       d       26
total update: updating composite
variable with a new value in a single step



              struct Date {
                int y, m, d;
              }
              struct Date today, tomorrow;
                                             C
              tomorrow = today;

              tomorrow.d = today.d + 1;




                         selective update: updating single
                         component of a composite variable
static array: array variable whose
index range is fixed at compile-time


float v1[] = {2.0, 3.0, 5.0, 7.0};
float v2[10];

void print_vector(float v[], int n) {
	 printf("[%3.2f", v[0]);
	 for(int i = 1; i < n; i++) {
	 	 printf(" %3.2f", v[i]);
	 }
	 printf("]");
}

print_vector(v1, 4);
print_vector(v2, 10);
                                        C
dynamic array: array variable whose index
range is fixed at the time when the array is created

type Vector is array (Integer range <>) of      Ada
Float;

v1: Vector(1 .. 4) := (2.0, 3.0, 5.0, 7.0);
v2: Vector(0 .. m) := (0 .. m => 0.0);

procedure print_vector(v: in Vector) is
-- Print the array v in the form "[...]".
begin
  put('['); put(v(v'first));
  for i in v'first + 1 .. v'last loop
     put(' '); put(v(i));
  end loop
  put(']');
end;
print_vector(v1); print_vector(v2);
flexible array: array variable whose index range is
  not fixed, may change when new array value is assigned


Java         float[] v1 = {2.0, 3.0, 5.0, 7.0};
             float[] v2 = {0.0, 0.0, 0.0};

             v1 = v2; // changes index range of v1

             static void printVector(float[] v) {
               System.out.print("[" + v[0]);
               for(int i = 1; i < v.length; i++) {
                 System.out.print(" " + v[i]);
               }
               System.out.print("]");
             }

             printVector(v1);
             printVector(v2);
Copy Semantics vs
Reference Semantics
copy semantics: assignment copies all
                        components of composite value into
            corresponding components of composite variable



     C      struct Date {
              int y, m, d;
            }
            struct Date dateA = {2013, 2, 31};
            struct Date dateB;
            dateB = dateA; // copy assignment

            struct Date *dateP   = malloc(sizeof(struct Date));
            struct Date *dateQ   = malloc(sizeof(struct Date));
            *dateP = dateA; //   copy assignment
            dateQ = dateP; //    reference assignment
draw this
class Date {
draw this          int y, m, d;
                   public Date(int y, int m, int d) {
                     // ...
                   }
                 }

                 Date dateR = new Date(2013, 1, 31);
                 Date dateS = new Date(2012, 11, 26);
                 dateS = dateR; // reference assignment

                 Date dateT = new Date(2013, 4, 9);
                 dateT = dateR.clone(); // copy assignment
Java

 reference semantics: assignment makes
 composite variable contain a pointer (or
 reference) to the composite value
equality test should be consistent
       with semantics of assignment



under copy semantics equality test is structural: tests
   whether corresponding components of two
           composite values are equal


      under reference semantics equality test
      tests whether the pointers to the two
            composite values are equal
Lifetime
lifetime of a variable: interval between creation
(allocation) and destruction (deallocation)

  global variable: declared for use throughout the
  program; lifetime is program’s run-time

  local variable: declared within a block, for use only
  within that block; lifetime is activation of block

  heap variable: can be created and destroyed at any
  time during the program’s run-time; arbitrary lifetime
  bound by program run-time

  persistent variable: lifetime transcends activation
  of a program
Persistent Memory
Persistent variables in WebDSL




WebDSL (http://webdsl.org) is a high-level web
programming language developed at TU Delft
entity Assignment {
                                       Persistent variables in WebDSL
  key         :: String (id)
  title       :: String (name, searchable)
  shortTitle :: String                                                              2
  description :: WikiText (searchable)
  course      -> CourseEdition (searchable)
  weight      :: Float (default=1.0)
  deadline    :: DateTime (default=null)
  // ...
                     3      http://department.st.ewi.tudelft.nl/weblab/assignment/752
}

page assignment(assign: Assignment, tab: String) {
  main{
    progress(assign, tab)                                                      1
    pageHeader{
      output(assign.title)
      breadcrumbs(assign)
    }
    // ...
  }                       objects are automatically persisted           in database
}
Local Memory



based on “Pointers and Memory” by Nick Parlante
Variable              Allocation and Deallocation
• holds value
• needs memory for storage during lifetime
Allocation

• obtain memory for storage of variable value
Deallocation

• give memory back
Error: use deallocated variable
Rules for Local Storage
Function call

• memory allocated for all locals
• locals = parameters + local variables
During execution of function

• memory for locals allocated even if
  another function is called
Function exit
                                          // Local storage example
• locals are deallocated                  int Square(int num) {
                                          	 int result;
• end of scope for locals is reached      	 result = num * num;
                                          	 return result;
                                          }
void Foo(int a) {
   // (1) Locals (a, i, scores) allocated when Foo runs

	   int i;

	   float scores[100];
    // This array of 100 floats is allocated locally.

	   a = a + 1; // (2) Local storage is used by the computation

	   for (i = 0; i < a; i++) {
	   	 Bar(i + a); // (3) Locals continue to exist undisturbed,
	   } // even during calls to other functions.

} // (4) The locals are all deallocated when the function exits.



                                                                   C
void X() {
	 int a = 1;
	 int b = 2;
	 // T1
	 Y(a);
	 // T3
	 Y(b);
	 // T5
}
void Y(int p) {
	 int q;
	 q = p + 2;
	 // T2 (first time through),
   // T4 (second time through)
}
                                 Stack Frames
Local Memory
Advantages

• Convenient: temporary memory for lifetime of function
• Efficient: fast allocation and deallocation, no waste of space
• Local copies: parameters are pass by value
Disadvantages

• Short lifetime: cannot be used for more permanent storage
• Restricted communication: cannot report back to caller
Synonyms

• “automatic” variables
• stack variables
Escaping Locals



   // TAB -- The Ampersand Bug function
   // Returns a pointer to an int
   int* TAB() {
   	 int temp;
   	 return (&temp); // return a pointer to the local int
   }
   void Victim() {
   	 int* ptr;
   	 ptr = TAB();
   	 *ptr = 42; // Runtime error! The pointee was local to TAB
   }
pop quiz: what is the significance of the number 42?
Memory and Pointers in C



    based on “Pointers and Memory” by Nick Parlante
Pointers and Addresses




             p = &c;
int x = 1, y = 2, z[10];

int *ip; /* ip is a pointer to int */

ip = &x; /* ip now points to x */

y = *ip; /* y is now 1 */

*ip = 0; /* x is now 0 */

ip = &z[0]; /* ip now points to z[0] */

*ip = *ip + 10; /* z[0] incremented with 10 */




                           Dereferencing Pointers
Pointers and Arrays   int a[10];
                      int *pa;
                      pa = &a[0];
                      x = *pa; // x == a[0]




                               Pointer Arithmetic
#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n) /* return pointer to n characters */
{
	 if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
	 	 allocp += n;
	 	 return allocp - n; /* old p */
	 } else
	 	 /* not enough room */
                                         Pointer Arithmetic
	 	 return 0;
}
void afree(char *p) /* free storage pointed to by p */
{
	 if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
	 	 allocp = p;
}
Heap Memory



based on “Pointers and Memory” by Nick Parlante
Heap memory = dynamic memory

• allocated at run-time
Advantages

• Lifetime: programmer controls memory allocation,
  deallocation

• Size: allocate amount of memory needed at run-time
Disadvantages

• More work: manage the heap
• More bugs: ... under control of programmer ...
Deallocation

Allocation
void Heap1() {
	 int* intPtr;
	 // Allocates local pointer local variable (but not its pointee)
	 // Allocates heap block and stores its pointer in local variable.
	 // Dereferences the pointer to set the pointee to 42.
	 intPtr = malloc(sizeof(int));
	 *intPtr = 42;
	 // Deallocates heap block making the pointer bad.
	 // The programmer must remember not to use the pointer
	 // after the pointee has been deallocated (this is
	 // why the pointer is shown in gray).
	 free(intPtr);
}
void Heap1() {
	 int* intPtr;
	 // Allocates local pointer local variable (but not its pointee)
	 // Allocates heap block and stores its pointer in local variable.
	 // Dereferences the pointer to set the pointee to 42.
	 intPtr = malloc(sizeof(int));
	 *intPtr = 42;
	 // Deallocates heap block making the pointer bad.
	 // The programmer must remember not to use the pointer
	 // after the pointee has been deallocated (this is
	 // why the pointer is shown in gray).
	 free(intPtr);
}
void Heap1() {
	 int* intPtr;
	 // Allocates local pointer local variable (but not its pointee)
	 // Allocates heap block and stores its pointer in local variable.
	 // Dereferences the pointer to set the pointee to 42.
	 intPtr = malloc(sizeof(int));
	 *intPtr = 42;
	 // Deallocates heap block making the pointer bad.
	 // The programmer must remember not to use the pointer
	 // after the pointee has been deallocated (this is
	 // why the pointer is shown in gray).
	 free(intPtr);
}
void Heap1() {
	 int* intPtr;
	 // Allocates local pointer local variable (but not its pointee)
	 // Allocates heap block and stores its pointer in local variable.
	 // Dereferences the pointer to set the pointee to 42.
	 intPtr = malloc(sizeof(int));
	 *intPtr = 42;
	 // Deallocates heap block making the pointer bad.
	 // The programmer must remember not to use the pointer
	 // after the pointee has been deallocated (this is
	 // why the pointer is shown in gray).
	 free(intPtr);
}
Memory Layout
Programming the Heap
Heap

• Area of memory to allocate blocks of memory for program
• Heap manager: manages internals of heap
• Free list: private data structure for heap management
• Heap may get full
  • requests for more memory fail
• Allocated block reserved for caller
  • location and size fixed
• Deallocation gives block back to heap manager
  • deallocated blocks should not be used
Memory Management API
         void *malloc(size_t n);
         // returns a pointer to n bytes of uninitialized storage,
         // or NULL if the request cannot be satisfied

         void *calloc(size_t n, size_t size);
         // returns a pointer to enough free space for
         // an array of n objects of the specified size,
         // or NULL if the request cannot be satisfied.
         // The storage is initialized to zero.

         void free(void *ap);
         // frees the space pointed to by p, where p was
         // originally obtained by a call to malloc or calloc.

         int *ip;
         ip = (int *) calloc(n, sizeof(int));
         // allocated memory should be cast to appropriate type




                                         K&R: a sample implementation
void HeapArray() {
	 struct fraction* fracts;
	 int i;
	 // allocate the array
	 fracts = malloc(sizeof(struct fraction) * 100);
	 // use it like an array -- in this case set them all to 22/7
	 for (i = 0; i < 99; i++) {
	 	 fracts[i].numerator = 22;
	 	 fracts[i].denominator = 7;
	 }
	 // Deallocate the whole array
	 free(fracts);
}




                           Allocating Array on Heap
/*
  Given a C string, return a heap allocated copy of the string.
  Allocate a block in the heap of the appropriate size,
  copies the string into the block, and returns a pointer to the block.
  The caller takes over ownership of the block and is responsible
  for freeing it.
  */
char* StringCopy(const char* string) {
	 char* newString;
	 int len;
	 len = strlen(string) + 1; // +1 to account for the '0'
	 newString = malloc(sizeof(char) * len);
     // elem-size * number-of-elements
                                                              dynamic size
	 assert(newString != NULL);
     // simplistic error check (a good habit)
	 strcpy(newString, string);
     // copy the passed in string to the block
	 return (newString); // return a ptr to the block
}                                                             long lifetime



                                      Allocating String on Heap
typedef long Align; /* for alignment to long boundary */

union header { /* block header */
	 struct {
	 	 union header *ptr; /* next block if on free list */
	 	 unsigned size; /* size of this block */
	 } s;
	 Align x; /* force alignment of blocks */
};
typedef union header Header;                            Free List
static Header base; /* empty list to get started */
static Header *freep = NULL; /* start of free list */
Memory is allocated, but not deallocated

     • heap gradually fills up
     • program runs out of heap space
     • crash
     Ownership

     • stringCopy() does not own allocated memory
     • caller is responsible for deallocation
     Memory management

     • requires careful administration of memory allocated
Memory Leaks
lifetime of a variable: interval between creation
(allocation) and destruction (deallocation)

  global variable: declared for use throughout the
  program; lifetime is program’s run-time

  local variable: declared within a block, for use only
  within that block; lifetime is activation of block

  heap variable: can be created and destroyed at any
  time during the program’s run-time; arbitrary lifetime
  bound by program run-time

  persistent variable: lifetime transcends activation
  of a program
Study Question: How is memory
  management arranged in Java,
      Scala, JavaScript, ...?
Reading & Programming in Week 3

Reading

  Sebesta C6: Data Types

  Programming in Scala Ch6: Functional Objects

  Parlante: Memory and pointers in C


WebLab:
  C, JavaScript, Scala tutorials
   Grammars and regular expressions



                                       Week 4: Data Types

Weitere ähnliche Inhalte

Was ist angesagt?

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 

Was ist angesagt? (19)

Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Java basic understand OOP
Java basic understand OOPJava basic understand OOP
Java basic understand OOP
 
Ti1220 Lecture 2
Ti1220 Lecture 2Ti1220 Lecture 2
Ti1220 Lecture 2
 
Basic c#
Basic c#Basic c#
Basic c#
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Oop rosenschein
Oop rosenscheinOop rosenschein
Oop rosenschein
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
08slide
08slide08slide
08slide
 
Op ps
Op psOp ps
Op ps
 
10slide
10slide10slide
10slide
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Java misc1
Java misc1Java misc1
Java misc1
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 

Andere mochten auch

Declare Your Language (at DLS)
Declare Your Language (at DLS)Declare Your Language (at DLS)
Declare Your Language (at DLS)
Eelco Visser
 

Andere mochten auch (9)

NaBL: A Meta-Language for Declarative Name Binding and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding  and Scope RulesNaBL: A Meta-Language for Declarative Name Binding  and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding and Scope Rules
 
IN4308 Lecture 3
IN4308 Lecture 3IN4308 Lecture 3
IN4308 Lecture 3
 
Name binding with scope graphs
Name binding with scope graphsName binding with scope graphs
Name binding with scope graphs
 
Linguistic Abstraction for the Web
Linguistic Abstraction for the WebLinguistic Abstraction for the Web
Linguistic Abstraction for the Web
 
A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...
 
Declare Your Language (at DLS)
Declare Your Language (at DLS)Declare Your Language (at DLS)
Declare Your Language (at DLS)
 
Separation of Concerns in Language Definition
Separation of Concerns in Language DefinitionSeparation of Concerns in Language Definition
Separation of Concerns in Language Definition
 
Dynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter GenerationDynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter Generation
 
Static name resolution
Static name resolutionStatic name resolution
Static name resolution
 

Ähnlich wie Lecture 3: Storage and Variables

Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
rsnyder3601
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
Manoj Kumar kothagulla
 
Vectors Intro.ppt
Vectors Intro.pptVectors Intro.ppt
Vectors Intro.ppt
puneet680917
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 

Ähnlich wie Lecture 3: Storage and Variables (20)

Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
P1
P1P1
P1
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
Vectors Intro.ppt
Vectors Intro.pptVectors Intro.ppt
Vectors Intro.ppt
 
34. uml
34. uml34. uml
34. uml
 
C questions
C questionsC questions
C questions
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 

Mehr von Eelco Visser

Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 

Mehr von Eelco Visser (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone Frameworks
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 

Kürzlich hochgeladen

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

Lecture 3: Storage and Variables

  • 1. Lecture 3: Variables and Storage TI1220 2012-2013 Concepts of Programming Languages Eelco Visser / TU Delft
  • 2. Outline Messages from the lab Variables & storage Copy & reference semantics Lifetime Local & heap memory Memory management (Memory and pointers in C)
  • 4.
  • 6. New release of WebLab New release of WebLab
  • 8. Deadline: final date that assignment can be submitted without penalty Due date (new): advise date for finishing assignment to help you plan your work
  • 10. A program variable is an abstraction of a computer memory cell or collection of cells
  • 11. Von Neumann Architecture: stored-program computer in which an instruction fetch and a data operation cannot occur at the same time because they share a common bus http://en.wikipedia.org/wiki/File:Computer_system_bus.svg
  • 12. Chapter 3: Variables and Storage
  • 13. Storage Cell unique address status: allocated or unallocated content: storable value or undefined primitive variable 63 ‘foo’ composite variable ? undefined false unallocated cell
  • 14. storable value: can be stored in single storage cell C++: primitive values and pointers Java: primitive values and pointers to objects Typically: composite values are not storable
  • 15. simple variable: a variable that may contain a storable value; occupies a single storage cell { ? int n; C n = 0; 0 n = n + 1; 1 } terminology: “the content of the storage cell denoted by n” ~ “the value of n”
  • 16. dates composite variable: a variable of a composite type, occupies a dates[0] y 2013 group of contiguous cells m 1 d 31 struct Date { dates[1] y 2013 int y, m, d; } C struct Date today; m 2 today.m = 2; today.d = 26; d 26 today.y = 2013; today dates[2] y ? struct Date dates[3]; y 2013 m ? dates[0].y = 2013; dates[0].m = 1; m 2 d ? dates[0].d = 31; dates[1] = today; d 26
  • 17. total update: updating composite variable with a new value in a single step struct Date { int y, m, d; } struct Date today, tomorrow; C tomorrow = today; tomorrow.d = today.d + 1; selective update: updating single component of a composite variable
  • 18. static array: array variable whose index range is fixed at compile-time float v1[] = {2.0, 3.0, 5.0, 7.0}; float v2[10]; void print_vector(float v[], int n) { printf("[%3.2f", v[0]); for(int i = 1; i < n; i++) { printf(" %3.2f", v[i]); } printf("]"); } print_vector(v1, 4); print_vector(v2, 10); C
  • 19. dynamic array: array variable whose index range is fixed at the time when the array is created type Vector is array (Integer range <>) of Ada Float; v1: Vector(1 .. 4) := (2.0, 3.0, 5.0, 7.0); v2: Vector(0 .. m) := (0 .. m => 0.0); procedure print_vector(v: in Vector) is -- Print the array v in the form "[...]". begin put('['); put(v(v'first)); for i in v'first + 1 .. v'last loop put(' '); put(v(i)); end loop put(']'); end; print_vector(v1); print_vector(v2);
  • 20. flexible array: array variable whose index range is not fixed, may change when new array value is assigned Java float[] v1 = {2.0, 3.0, 5.0, 7.0}; float[] v2 = {0.0, 0.0, 0.0}; v1 = v2; // changes index range of v1 static void printVector(float[] v) { System.out.print("[" + v[0]); for(int i = 1; i < v.length; i++) { System.out.print(" " + v[i]); } System.out.print("]"); } printVector(v1); printVector(v2);
  • 22. copy semantics: assignment copies all components of composite value into corresponding components of composite variable C struct Date { int y, m, d; } struct Date dateA = {2013, 2, 31}; struct Date dateB; dateB = dateA; // copy assignment struct Date *dateP = malloc(sizeof(struct Date)); struct Date *dateQ = malloc(sizeof(struct Date)); *dateP = dateA; // copy assignment dateQ = dateP; // reference assignment draw this
  • 23. class Date { draw this int y, m, d; public Date(int y, int m, int d) { // ... } } Date dateR = new Date(2013, 1, 31); Date dateS = new Date(2012, 11, 26); dateS = dateR; // reference assignment Date dateT = new Date(2013, 4, 9); dateT = dateR.clone(); // copy assignment Java reference semantics: assignment makes composite variable contain a pointer (or reference) to the composite value
  • 24. equality test should be consistent with semantics of assignment under copy semantics equality test is structural: tests whether corresponding components of two composite values are equal under reference semantics equality test tests whether the pointers to the two composite values are equal
  • 26. lifetime of a variable: interval between creation (allocation) and destruction (deallocation) global variable: declared for use throughout the program; lifetime is program’s run-time local variable: declared within a block, for use only within that block; lifetime is activation of block heap variable: can be created and destroyed at any time during the program’s run-time; arbitrary lifetime bound by program run-time persistent variable: lifetime transcends activation of a program
  • 28. Persistent variables in WebDSL WebDSL (http://webdsl.org) is a high-level web programming language developed at TU Delft
  • 29. entity Assignment { Persistent variables in WebDSL key :: String (id) title :: String (name, searchable) shortTitle :: String 2 description :: WikiText (searchable) course -> CourseEdition (searchable) weight :: Float (default=1.0) deadline :: DateTime (default=null) // ... 3 http://department.st.ewi.tudelft.nl/weblab/assignment/752 } page assignment(assign: Assignment, tab: String) { main{ progress(assign, tab) 1 pageHeader{ output(assign.title) breadcrumbs(assign) } // ... } objects are automatically persisted in database }
  • 30. Local Memory based on “Pointers and Memory” by Nick Parlante
  • 31. Variable Allocation and Deallocation • holds value • needs memory for storage during lifetime Allocation • obtain memory for storage of variable value Deallocation • give memory back Error: use deallocated variable
  • 32. Rules for Local Storage Function call • memory allocated for all locals • locals = parameters + local variables During execution of function • memory for locals allocated even if another function is called Function exit // Local storage example • locals are deallocated int Square(int num) { int result; • end of scope for locals is reached result = num * num; return result; }
  • 33. void Foo(int a) { // (1) Locals (a, i, scores) allocated when Foo runs int i; float scores[100]; // This array of 100 floats is allocated locally. a = a + 1; // (2) Local storage is used by the computation for (i = 0; i < a; i++) { Bar(i + a); // (3) Locals continue to exist undisturbed, } // even during calls to other functions. } // (4) The locals are all deallocated when the function exits. C
  • 34. void X() { int a = 1; int b = 2; // T1 Y(a); // T3 Y(b); // T5 } void Y(int p) { int q; q = p + 2; // T2 (first time through), // T4 (second time through) } Stack Frames
  • 35. Local Memory Advantages • Convenient: temporary memory for lifetime of function • Efficient: fast allocation and deallocation, no waste of space • Local copies: parameters are pass by value Disadvantages • Short lifetime: cannot be used for more permanent storage • Restricted communication: cannot report back to caller Synonyms • “automatic” variables • stack variables
  • 36. Escaping Locals // TAB -- The Ampersand Bug function // Returns a pointer to an int int* TAB() { int temp; return (&temp); // return a pointer to the local int } void Victim() { int* ptr; ptr = TAB(); *ptr = 42; // Runtime error! The pointee was local to TAB }
  • 37. pop quiz: what is the significance of the number 42?
  • 38. Memory and Pointers in C based on “Pointers and Memory” by Nick Parlante
  • 40. int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to int */ ip = &x; /* ip now points to x */ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ ip = &z[0]; /* ip now points to z[0] */ *ip = *ip + 10; /* z[0] incremented with 10 */ Dereferencing Pointers
  • 41. Pointers and Arrays int a[10]; int *pa; pa = &a[0]; x = *pa; // x == a[0] Pointer Arithmetic
  • 42. #define ALLOCSIZE 10000 /* size of available space */ static char allocbuf[ALLOCSIZE]; /* storage for alloc */ static char *allocp = allocbuf; /* next free position */ char *alloc(int n) /* return pointer to n characters */ { if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */ allocp += n; return allocp - n; /* old p */ } else /* not enough room */ Pointer Arithmetic return 0; } void afree(char *p) /* free storage pointed to by p */ { if (p >= allocbuf && p < allocbuf + ALLOCSIZE) allocp = p; }
  • 43. Heap Memory based on “Pointers and Memory” by Nick Parlante
  • 44. Heap memory = dynamic memory • allocated at run-time Advantages • Lifetime: programmer controls memory allocation, deallocation • Size: allocate amount of memory needed at run-time Disadvantages • More work: manage the heap • More bugs: ... under control of programmer ...
  • 46. void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); }
  • 47. void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); }
  • 48. void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); }
  • 49. void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); }
  • 51. Programming the Heap Heap • Area of memory to allocate blocks of memory for program • Heap manager: manages internals of heap • Free list: private data structure for heap management • Heap may get full • requests for more memory fail • Allocated block reserved for caller • location and size fixed • Deallocation gives block back to heap manager • deallocated blocks should not be used
  • 52. Memory Management API void *malloc(size_t n); // returns a pointer to n bytes of uninitialized storage, // or NULL if the request cannot be satisfied void *calloc(size_t n, size_t size); // returns a pointer to enough free space for // an array of n objects of the specified size, // or NULL if the request cannot be satisfied. // The storage is initialized to zero. void free(void *ap); // frees the space pointed to by p, where p was // originally obtained by a call to malloc or calloc. int *ip; ip = (int *) calloc(n, sizeof(int)); // allocated memory should be cast to appropriate type K&R: a sample implementation
  • 53. void HeapArray() { struct fraction* fracts; int i; // allocate the array fracts = malloc(sizeof(struct fraction) * 100); // use it like an array -- in this case set them all to 22/7 for (i = 0; i < 99; i++) { fracts[i].numerator = 22; fracts[i].denominator = 7; } // Deallocate the whole array free(fracts); } Allocating Array on Heap
  • 54. /* Given a C string, return a heap allocated copy of the string. Allocate a block in the heap of the appropriate size, copies the string into the block, and returns a pointer to the block. The caller takes over ownership of the block and is responsible for freeing it. */ char* StringCopy(const char* string) { char* newString; int len; len = strlen(string) + 1; // +1 to account for the '0' newString = malloc(sizeof(char) * len); // elem-size * number-of-elements dynamic size assert(newString != NULL); // simplistic error check (a good habit) strcpy(newString, string); // copy the passed in string to the block return (newString); // return a ptr to the block } long lifetime Allocating String on Heap
  • 55. typedef long Align; /* for alignment to long boundary */ union header { /* block header */ struct { union header *ptr; /* next block if on free list */ unsigned size; /* size of this block */ } s; Align x; /* force alignment of blocks */ }; typedef union header Header; Free List static Header base; /* empty list to get started */ static Header *freep = NULL; /* start of free list */
  • 56. Memory is allocated, but not deallocated • heap gradually fills up • program runs out of heap space • crash Ownership • stringCopy() does not own allocated memory • caller is responsible for deallocation Memory management • requires careful administration of memory allocated Memory Leaks
  • 57. lifetime of a variable: interval between creation (allocation) and destruction (deallocation) global variable: declared for use throughout the program; lifetime is program’s run-time local variable: declared within a block, for use only within that block; lifetime is activation of block heap variable: can be created and destroyed at any time during the program’s run-time; arbitrary lifetime bound by program run-time persistent variable: lifetime transcends activation of a program
  • 58. Study Question: How is memory management arranged in Java, Scala, JavaScript, ...?
  • 59. Reading & Programming in Week 3 Reading Sebesta C6: Data Types Programming in Scala Ch6: Functional Objects Parlante: Memory and pointers in C WebLab: C, JavaScript, Scala tutorials Grammars and regular expressions Week 4: Data Types