cs 314 principles of programming languages lecture 10 · cs 314 principles of programming languages...
TRANSCRIPT
CS 314 Principles of Programming Languages
Lecture 10
Zheng Zhang
Department of Computer ScienceRutgers University
Friday 7th October, 2016
Zheng Zhang 1 CS@Rutgers University
Class Information
I Homework 1 grades and sample solution released.
I Homework 4 will be released by the end of today.
I First project will be posted by the end of this week.
I Midterm exam: Friday October 28 (tentative), in class, closedbook, closed notes.
Zheng Zhang 2 CS@Rutgers University
Homework 2 Extra-credit
I Section 1: Min Chai, Krishna Patel, Karl Xu.
I Section 2: Akhila Narayan, Azizur Rahman, BhavinkumarHirpara, Christian Suasi, Elina Chhabra, Heman Gandhi, RajPatel, Renard Tumbokon.
I Section 3: Xinran Shi, David Domingo
Zheng Zhang 3 CS@Rutgers University
Review: Syntax Directed Translation
Examples:
1. Interpreter
2. Code generator
3. Type checker
4. Performance estimator
Use hand-written recursive descent LL(1) parser
Zheng Zhang 4 CS@Rutgers University
Review - Example: LL(1) Parser For Prefix Expression
1: <expr> ::= + <expr> <expr> |2: <digit>3: <digit> :: = 0 | 1 | 2 | 3 | . . . | 9
+ 0..9 other
<expr> r1 r2 error<digit> error r3 error
void expr( ): // returns value of expressionint val1, val2; // valuesswitch token {
case +: token := next token( );expr( ); expr( );
case 0..9: digit( );. . .
}
void digit( ): // returns value of constantswitch token {
case 1: token := next token( );case 2: token := next token( );. . .
}Zheng Zhang 5 CS@Rutgers University
Review - Example: Simple Code Generation
<expr> ::= + <expr> <expr> |<digit>
<digit> :: = 0 | 1 | 2 | 3 | . . . | 9
int expr: // returns target register of operationint target reg;// “fresh” registerint reg1, reg2; // other registersswitch token {
case +: token := next token( );target reg = next register( );reg1 = expr( ); reg2 = expr( );CodeGen(ADD, reg1, reg2, target reg);return target reg;
case 0..9: return digit( );. . .
}
int digit: // returns target register of operationint target reg; // “fresh” registerswitch token {
case 1: token := next token( );target reg = next register( );CodeGen(LOADI, 1, target reg);return target reg;
case 2: token := next token( );target reg = next register( );CodeGen(LOADI, 2, target reg);return target reg;
. . .}
Zheng Zhang 6 CS@Rutgers University
Review - Example: Simple Code Generation
What happens when you parse subprogram“+ 2 + 1 2” ?
Assumption:first call to next register( ) will return 1
The parsing produces:
LOADI 2 => r2
LOADI 1 => r4
LOADI 2 => r5
ADD r4, r5 => r3
ADD r2, r3 => r1
Zheng Zhang 7 CS@Rutgers University
Review: Imperative Programming Languages
Imperative: Sequence of state-changing actions.I Manipulate an abstract machine with:
1. Variables naming memory locations2. Arithmetic and logical operations3. Reference, evaluate, assign operations4. Explicit control flow statements
I Key operations: Assignment and “Goto”I Fits the von Neumann architecture closely
Von Neumann Architecture
Zheng Zhang 8 CS@Rutgers University
Review - C: An Imperative Programming Language
Expressions: include procedure and function calls andassignments.
Control Structures:
I if statements, with and without else clauses
I loops, with break and continue exits
while ( <expr> ) <stmt>do <stmt> while ( <expr> )for ( <expr> ; <expr> ; <expr> ) <stmt>
I switch statements
I goto with labelled branch targets
Zheng Zhang 9 CS@Rutgers University
Review: Pointers in C
Pointer: Variable whose R-values (content) is the L-value(address) of a variable
I “address-of” operator &
I dereference (“content-of”) operator ∗
5p x
*p = 5;
p = &x;
p xint *p, x;
x = 12;p x
12
Zheng Zhang 10 CS@Rutgers University
Stack vs. Heap
Stack:
I Procedure activations, statically allocated local variables,parameter values
I Lifetime same as subroutine in which variables are declared
I Stack frame is pushed with each invocation of a subroutine,and popped after subroutine exit
Heap:
I Dynamically allocated data structures, whose size may not beknown in advance
I Lifetime extends beyond subroutine in which they are created
I Must be explicitly freed or garbage collected
Zheng Zhang 11 CS@Rutgers University
Maintaining Free List
I allocate: continuous block of memory; remove space fromfree list (here: singly-linked list).
I free: return to free list after coalescing with adjacent freestorage (if possible); may initiate compaction.
Zheng Zhang 12 CS@Rutgers University
Maintaining Free List
free space pointerALLOCATE
free space pointer
free space pointerFREE
free space pointer
Zheng Zhang 13 CS@Rutgers University
Problems with Explicit Control of Heap
I Dangling referencesI Storage pointed to is freed, but pointer (or reference) is not
set to NULLI Able to access storage whose values are not meaningful
I GarbageI Objects in heap that cannot be accessed by the program any
moreI Example
int *x, *y;
x = (int *) malloc(sizeof(int));
y = (int *) malloc(sizeof(int));
x = y;
I Memory leaksI Failure to release (reclaim) memory storage builds up over time
Zheng Zhang 14 CS@Rutgers University
Example: Singly-linked list
Let’s deallocate, i.e., free all list elements.
#include "list.h"
/* GLOBAL VARIABLES */
listcell *head, *new_cell, *current_cell;
int main (void) {
int j;
/* CREATE FIRST LIST ELEMENT */
. . .
/* CREATE 9 MORE ELEMENTS */
. . .
/* DEALLOCATE LIST */
for (current_cell = head;
current_cell != NULL;
current_cell = current_cell->next)
free(current_cell);
}
. . .
}
Does this work?Zheng Zhang 15 CS@Rutgers University
What went wrong?
Uninitialized variables and “dangerous” casting
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a;
*a = 12;
printf("%x %x: %d\n", &a, a, *a);
a = (int *) 12;
printf("%d\n", *a);
}
> a.outeffff60c effff68c: 12
Segmentation fault (core dumped)
Note: Segmentation faults result in the generation of a core filewhich can be rather large. Don’t forget to delete it.Zheng Zhang 16 CS@Rutgers University
What went wrong?
That’s better!
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a = NULL; /* good practice */
a = (int *) malloc(sizeof(int));
*a = 12;
printf("%x %x: %d\n", &a, a, *a);
}
> a.outeffff60c 20900: 12
Zheng Zhang 17 CS@Rutgers University
What went wrong?
The machine or compiler must be broken!?!!
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i;
char *string = "Hello, how are you today.";
printf("\n%s\n", string);
for (i=0; string[i] != ’.’; i++) {
if (string[i] = ’ ’)
for (; string[i] = ’ ’;i++);
printf("%c", string[i]);
}
printf(".\n");
}
> a.outHello, how are you today.
Segmentation fault (core dumped)Zheng Zhang 18 CS@Rutgers University
What went wrong?
“=” is not the same as “==”
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i;
char *string = "Hello, how are you today.";
printf("\n%s\n", string);
for (i=0; string[i] != ’.’; i++) {
if (string[i] == ’ ’)
for (; string[i] == ’ ’;i++);
printf("%c", string[i]);
}
printf(".\n");
}
> a.outHello, how are you today.
Hello,howareyoutoday.Zheng Zhang 19 CS@Rutgers University
What went wrong?“Aliasing” and freeing memory#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a = NULL; int *b = NULL; int *c = NULL;
a = (int *) malloc(sizeof(int));
b = a; *a = 12;
printf("%x %x: %d\n", &a, a, *a);
printf("%x %x: %d\n", &b, b, *b);
free(a);
printf("%x %x: %d\n", &b, b, *b);
c = (int *) malloc(sizeof(int));
*c = 10;
printf("%x %x: %d\n", &c, c, *c);
printf("%x %x: %d\n", &b, b, *b);
}
> a.outeffff60c 209d0: 12effff608 209d0: 12effff608 209d0: 12
effff604 209d0: 10 effff608 209d0: 10
Zheng Zhang 20 CS@Rutgers University
What went wrong?
Use a subroutine to create an object
#include <stdio.h>
#include <stdlib.h>
/* TYPE DEFINITION */
typedef struct cell listcell;
struct cell
{ int num;
listcell *next;
};
listcell *head = NULL;
listcell *create_listcell() {
listcell new;
new.num = -1; new.next = NULL;
return &new;
}
int main (void) {
head = create_listcell();
printf("head->num = %d\n", head->num);
}
> gcc stack.cstack.c: In function ‘create listcell’:stack.c:17: warning: function returns address of local variable
> ./a.out
head→num = -1
Zheng Zhang 21 CS@Rutgers University
What went wrong?
Use a subroutine to create an object: malloc
#include <stdio.h>
#include <stdlib.h>
/* TYPE DEFINITION */
typedef struct cell listcell;
struct cell
{ int num;
listcell *next;
};
listcell *head = NULL;
listcell *create_listcell() {
listcell *new;
new = (listcell *) malloc(sizeof(listcell));
new->num = -1; new->next = NULL;
return new;
}
int main (void) {
head = create_listcell();
printf("head->num = %d\n", head->num);
}
> gcc heap.c> ./a.out
head→num = -1
Zheng Zhang 22 CS@Rutgers University
Pointers and Arrays in C
Pointers and arrays are similar in C:I array name is pointer to a[0]:
after
int a[10];int *pa;pa = &a[0];
pa and a have the same semantics
I pointer arithmetic is array indexing
pa+1 and a+1 point to a[1]
I exception: an array name is a constant pointer
a++ is ILLEGALa=pa is ILLEGAL (pa=a is LEGAL!)
Zheng Zhang 23 CS@Rutgers University