PRINCIPLES OF PROGRAMMING LANGUAGES
UNIT-3
                                 Storage Management
Storage Management is defined as it refers to the management of the data storage equipment’s
that are used to store the user/computer generated data. Hence it is a tool or set of processes used
by an administrator to keep your data and storage equipment’s safe.
Storage management is a process for users to optimize the use of storage devices and to protect
the integrity of data for any media on which it resides and the category of storage management
generally contain the different type of subcategories covering aspects such as security,
virtualization and more, as well as different types of provisioning or automation, which is
generally made up the entire storage management software market.
Storage management key attributes:
Storage management has some key attribute which is generally used to manage the storage
capacity of the system. These are given below:
1. Performance
2. Reliability
3. Recoverability
4. Capacity
Feature of Storage management:
There is some feature of storage management which is provided for storage capacity. These are
given below:
  1. Storage management is a process that is used to optimize the use of storage devices.
  2. Storage management must be allocated and managed as a resource in order to truly benefit
     a corporation.
  3. Storage management is generally a basic system component of information systems.
  4. It is used to improve the performance of their data storage resources.
Advantage of storage management:
There are some advantage of storage management which are given below:
 • It is very simple to managed a storage capacity.
 • It is generally take a less time.
 • It is improve the performance of system.
 • In virtualization and automation technologies can help an organization improve its agility.
Static and dynamic memory management
Static Memory Allocation: Memory is allocated for the declared variable by the compiler. The
address can be obtained by using ‘address of’ operator and can be assigned to a pointer. The
memory is allocated during compile time. Since most of the declared variables have static
memory, this kind of assigning the address of a variable to a pointer is known as static memory
allocation.
Dynamic Memory Allocation: Allocation of memory at the time of execution (run time) is
known as dynamic memory allocation. The functions calloc() and malloc() support allocating of
dynamic memory. Dynamic allocation of memory space is done by using these functions when
value is returned by functions and assigned to pointer variables.
              Tabular Difference Between Static and Dynamic Memory Allocation in C:
  S.No         Static Memory Allocation           Dynamic Memory Allocation
               In the static memory allocation,   In the Dynamics memory allocation,
  1            variables get allocated            variables get allocated only if your program
               permanently.                       unit gets active.
               Static Memory Allocation is        Dynamics Memory Allocation is done during
  2
               done before program execution.     program execution.
               It uses stack for managing the     It uses heap for managing the dynamic
  3
               static allocation of memory        allocation of memory
  4            It is less efficient               It is more efficient
                                                  In Dynamics Memory Allocation, there is
               In Static Memory Allocation,
  5                                               memory re-usability and memory can be
               there is no memory re-usability
                                                  freed when not required
               In static memory allocation,       In dynamic memory allocation, when
  6            once the memory is allocated,      memory is allocated the memory size can be
               the memory size can not change.    changed.
                                                  This allows reusing the memory. The user
               In this memory allocation
                                                  can allocate more memory when required.
  7            scheme, we cannot reuse the
                                                  Also, the user can release the memory when
               unused memory.
                                                  the user needs it.
               In this memory allocation
                                                  In this memory allocation scheme, execution
  8            scheme, execution is faster than
                                                  is slower than static memory allocation.
               dynamic memory allocation.
               In this memory is allocated at
  9                                               In this memory is allocated at run time.
               compile time.
               In this allocated memory
                                                  In this allocated memory can be released at
  10           remains from start to end of the
                                                  any time during the program.
               program.
            Example: This static memory
                                                Example: This dynamic memory allocation
  11        allocation is generally used
                                                is generally used for linked list.
            for array.
Stack based memory management
Stack Allocation : The allocation happens on contiguous blocks of memory. We call it stack
memory allocation because the allocation happens in function call stack. The size of memory to
be allocated is known to compiler and whenever a function is called, its variables get memory
allocated on the stack. And whenever the function call is over, the memory for the variables is
deallocated. This all happens using some predefined routines in compiler. Programmer does not
have to worry about memory allocation and deallocation of stack variables.
Heap based memory management
Heap Allocation : The memory is allocated during execution of instructions written by
programmers. Note that the name heap has nothing to do with heap data structure. It is called
heap because it is a pile of memory space available to programmers to allocated and de-
allocate. If a programmer does not handle this memory well, memory leak can happen in the
program.
Key Differences Between Stack and Heap Allocations
 1. In a stack, the allocation and deallocation is automatically done by whereas, in heap, it
    needs to be done by the programmer manually.
 2. Handling of Heap frame is costlier than handling of stack frame.
 3. Memory shortage problem is more likely to happen in stack whereas the main issue in heap
    memory is fragmentation.
 4. Stack frame access is easier than the heap frame as the stack have small region of memory
    and is cache friendly, but in case of heap frames which are dispersed throughout the
    memory so it cause more cache misses.
 5. Stack is not flexible, the memory size allotted cannot be changed whereas a heap is
    flexible, and the allotted memory can be altered.
 6. Accessing time of heap takes is more than a stack.
Comparison Chart:
          PARAMETER                        STACK                               HEAP
                             Memory is allocated in a             Memory is allocated in any
  Basic
                             contiguous block.                    random order.
  Allocation and             Automatic by compiler
                                                                  Manual by programmer.
  Deallocation               instructions.
  Cost                       Less                                 More
  Implementation             Hard                                 Easy
      PARAMETER                      STACK                  HEAP
Access time             Faster               Slower
Main Issue              Shortage of memory   Memory fragmentation
Locality of reference   Excellent            Adequate
Flexibility             Fixed size           Resizing is possible
Data type structure     Linear               Hierarchical
                                   Sequence Control
The control of execution of the operations, both primitive and user defined, is termed as
sequence control.
Sequence control structures are categorized into following four groups:
1. Expressions: These form the basic building blocks for statements and express how at are
manipulated and changed by a program. Properties such as precedence rules and parentheses
determine how expressions become evaluated.
2. Statement: Statements such as conditional or iterative statements, determine how control
flows from one segment of a program to another.
3. Declarative programming: It is an execution model that does not depend on statements,
but nevertheless causes execution to proceed through a program.
4. Subprograms: Subprograms such as subprogram calls and coroutines, form a way to transfer
control from one segment of a program to another.
Implicit and Explicit Sequence Control:
Sequence control structures may be either implicit or explicit.
i) Implicit sequence-control structures:
These are defined by language to be in effect ’un1es'smodified by the programmer through
some explicit structure. For example, most languages define the physical sequence of
statements in a program as controlling the sequence in which statements are executed, unless
modified by an explicit sequence-control statement.
ii) Explicit sequence-control structure
These are the sequence-control structures that the programmer may optionally use to modify
the implicit sequence of operations defined by the language.
Implicit and explicit sequencing with arithmetic expressions
   ➢ Prefix Notation
        • Operators come first, then the operands
        • e.g. (a + b) * (c - a) => * + a b - c a
        • No ambiguity and no parenthesis needed
        • Number of arguments for an operator must be known a priori
        • Relatively easy to decode using stack mechanism
   ➢ Postfix notation
        • An operator follows its operands
        • e.g. (a+b) *(c-a) => a b + c a - *
        • No ambiguity and no parenthesis needed
      • Relatively easy to decode using stack mechanism
➢ Infix notation
      • Only suitable for binary operations (Thus used with prefix)
      • For more than one infix operator, it is inherently ambiguous
      • Parenthesis is used to explicitly annotate the order
➢ Implicit control rules
     • Hierarchy of operations (precedence) e.g. Ada
             o **, abs, not : Exponential absolute negation
             o * / mod : Multiplication, division,
             o + - : Unary addition and subtraction
             o + - & : Binary addition and subtraction
             o = < > : Relational
             o and or xor : Boolean operatins
     • Associative
             o left-right associativity (+, -, others)
             o right-left associativity (exponential)
➢ Issues in Evaluating Expressions
     • Uniform Evaluation rules (eager and lazy)
             o Eager Evaluation: evaluate the operands as soon as they appear
                (parallel processing SNOBOL)
             o Lazy Evaluation: Delay evaluation of operands as late as possible
                (LISP)
              o   foo( x )
                  { ...
                  if ( a > 0 )
                  a = x;
                  else a = a + 1;
                  }
                  foo( b/a );
       •   Side effects
              o a * foo(x) + a; say a= 1; foo(x) generates 3
                      ▪ if each term is evaluated 1 * 3 + 2 = 5
                      ▪ if a is evaluated only once 1 * 3 + 1 = 4
                      ▪ if evaluate foo(x) first 2 * 3 + 2 = 8
       •   Error Condition: No solution other than exceptional statements
       •   Short-circuit expression: Use the characteristics of “and” or “or” operation
       •   a b - a is true b is not evaluated
       •   a && b - a is false b is not evaluated
       •   e.g.
           b = 9;
           if ( a = 4 b = 3 )
           printf (" a = %d b = %d\n");
Implicit and explicit sequencing with non-arithmetic expressions
    ➢ Pattern Matching
      Pattern matching operation: An operation matches and assigns a set of variables to a
      predefined template
        e.g. (palindromes)
        A -> 0A0 1A1 0 1
        matches 00100 -> 00A00 -> 0A0 -> A
        applied term rewriting 00A00 is a term rewrite of 00100
        term rewriting: A restricted form of pattern match
        e.g. Given string a1a2a3a4 and α -> β.
        if α = a3 then a1a2βa4
        we say a1a2βa4 is term rewrite of a1a2a3a4
        e.g.) in ML
        fun fact(1) = 1
        fact(N:int) = N * fact(N - 1);
        fun length( nil ) = 0
        length( a :: y) = 1 + length( y )
        Unification and substitution: In Prolog, Database consists of facts and rules
        Substitution: replacement of a string to another one
        Unification: A pattern match to determine if the query has a valid substitution consistent
        with the rules and facts in the database
        Fact : ParentOf( Ann, John) ParentOf( Sam, Ann)
        Fact : ParentOf( Tom, John)
        Query : ParentOf( x, John)
        Þ X = Ann, x = Tom
        Rule : GrandOarentOf( X,Y) :- ParentOf(X,Z), ParentOf(Z,Y)
        then query : GrandParentOf (x,John) => x = sam
    ➢ Backtracking
      Backup to the previous subgoal that matched and try another possible goal for it to
      match when current subgoal is failed.
Sequence control between statements
Basic Statements
Basic statements are assignments, subprogram calls, and input and output statements. Within a basic
statement, sequences of operations may be invoked by using expressions.
Assignments to Data Objects
Change the computation by assigning values to data objects is major mechanism that affects the state of
computation by programs.
Assignment statements
The primary purpose of an assignment is to assign to the L-value of a data object, the R-value of some
expression.
The assignment operations are
A:=B // Pascal, Ada
A=B // C, FORTRAN, PL/I, Prolog, ML, SNOBOL4
MOVE B TO A // COBOL
A<- B // APL
And also
A=B;
A+=B
++A;
A++; these are all the assignment statements are available.
Input statement
All the languages include a statement form for reading data from the user at a terminal, from files, or from
a communications line. Such statements also change the values of variables through assignments.
Other assigning operations
Parameter transmission is often defined as assignment of the argument value to the formal parameter.
Various forms of implicit are found as well;
Forms of Statement-Level Sequence Control
The three main statement-level sequence controls are:
    1. Composition
       Statement may be placed in a textual sequence so that they are executed in order whenever the
       larger program structure containing the sequence is executed.
    2. Alternation
       Two sequences of statements may form alternatives so that one or the other sequence is executed,
       but not both.
       Eg., if statements.
    3. Iteration
       All looping statements are iterative statements. The control repetitively executes a statement at,
       ‘n' number of times.
Explicit Sequence Control
    1. GOTO
       The programmer can able to transfer the control explicitly. ‘Goto' the best example for explicit
       sequence controls.
    2. Break statement.
       Usually the break causes control to move forward in the program to an explicit point at the end of
        a given control structure. Thus, break in C causes control to exit the immediately enclosing while,
        for, or switch statement.
Structured programming Design
The Goto and Break statement spoils the hierarchy of programming structure.
Disadvantages of GOTO statements
1. Lack of hierarchical program structure.
2. Order of statements in the program text need not correspond to the order of execution.
3. Group of statements may serve multiple purposes.
Structured Sequence Control
    1. Compound Statements
       Is a sequence of statements that may be treated as a single statement in the construction of larger
       statements.
        e.g., begin
        Statement 1.
        Statement 2 // IN Pascal
        Statement n
        End;
        And similarly
        {
        // Braces In C and C++ and JAVA
        }
        Within the compound statement, statements are written in the order in which they are to be
        executed.
    2. Conditional Statements
        A conditional statement is one that expresses alternation of two or more statements, or optional
        execution of a single statement;
        // IF statements and IF then Else Statements.
    3. Case statements
        Iteration Statements
        Simple repetition.
        In COBOL
        Perform body K times
        Here, the body of the statements are executes ‘K' times.
        Repetition while condition holds
    Eg., while (x!='y'||x!='Y')
    {
    Statements;
    }
4. Repetition while incrementing a counter
    E.g., for (I=1;I<=n;I++)
    The I++ is a counter.
5. Indefinite repetition
   The loop will execute infinite number of times.
   E.g.,
    N=2;
    For (I=1;I<=n; n++)
    {
    Statements;
    }
6. Implementation of loop statements
   Implementation of loop-control statements using the hardware branch/jump instruction is
   straightforward. To implement a for loop, the expressions in the loop head defining the final
   value and increment must be evaluated on initial entry to the loop and saved in special temporary
   storage areas.
                                     Subprogram control
Subprogram Sequence Control
Now we are going to discuss about the simple mechanisms for sequencing between tow
subprograms, how on subprogram invokes another and called subprogram returns to the first. The
simple Call and return statements structure is common for all the subprograms
Simple subprograms call return.
1. Subprograms cannot be recursive
A subprogram is directly recursive if it contains a call on itself; it is indirectly recursive if it calls
another subprogram that calls the original subprogram or that initiates a further chain of
subprogram calls that eventually leads back to a call of the original subprogram.
1. Explicit call statements are required.
2. Subprograms must execute completely at each call.
3. Immediate transfer of control at point of call.
4. Single execution sequence.
Simple Call-Return Subprograms
Implementation
Current-instruction pointer.
Current-environment pointer
Stack-Based Implementation
Recursive Subprograms
Specification
Implementation
The Pascal Forward Declaration
Data Control and referencing environments
ATTRIBUTES OF DATA CONTROL
Names and Referencing Environments
Program Elements That may be named
Associations and Referencing Environments
Referencing environments
1. Local referencing environment
2. Nonlocal referencing environment
3. Global referencing environment
4. Predefined referencing environment
Visibility
Dynamic scope
Referencing operations
Local, nonlocal, and global references.
Aliases for Data Objects
Static and Dynamic Scope
The importance of static scope
Block Structure
Local Data and Local Referencing Environments
Implementation
Deletion
1. Individual variables
2. A subprogram name
3. A formal-parameter
4. recursive subprogram
Advantages and Disadvantages
Parameter transmission/Parameter passing
Actual and Formal Parameter
Establishing the Correspondence
Positional correspondence
Correspondence by explicit name
Method for Transmitting Parameters
Call by name
Call by reference
Call by value
Call by value-result
Call by constant value
Call by result
Transmission Semantics
Elementary data types
Composite data types
Explicit Function Values
Implementation of Parameter Transmission
Parameter Transmission Examples
Simple variables and constants
Data structures
Components of data structures
Aliases and Parameters
Subprograms as Parameters
Statement Labels as Parameters
static and dynamic scope
Block structure
In computer programming, a block or code block is a lexical structure of source code which is
grouped together. Blocks consist of one or more declarations and statements. A programming
language that permits the creation of blocks, including blocks nested within other blocks, is called
a block-structured programming language. Blocks are fundamental to structured programming,
where control structures are formed from blocks.
The function of blocks in programming is to enable groups of statements to be treated as if they
were one statement, and to narrow the lexical scope of objects such as variables, procedures and
functions declared in a block so that they do not conflict with those having the same name used
elsewhere. In a block-structured programming language, the objects named in outer blocks are
visible inside inner blocks, unless they are masked by an object declared with the same name.