Memory layout. int foo() { int b; } int main() { int a; foo(); Program. Stack. Heap. foo: int b main: int a

Similar documents
Outline. Pointers arithme.c and others Func.ons & pointers

CS16 Exam #1 7/17/ Minutes 100 Points total

Machine Program: Procedure. Zhaoguo Wang

Stack Frame Components. Using the Stack (4) Stack Structure. Updated Stack Structure. Caller Frame Arguments 7+ Return Addr Old %rbp

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

The Compilation Process

Technical Questions. Q 1) What are the key features in C programming language?

Areas for growth: I love feedback

The Stack & Procedures

Concurrency. Johan Montelius KTH

by Pearson Education, Inc. All Rights Reserved.

Program Translation. text. text. binary. binary. C program (p1.c) Compiler (gcc -S) Asm code (p1.s) Assembler (gcc or as) Object code (p1.

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

CS429: Computer Organization and Architecture

Advanced Pointer Topics

GCC and Assembly language. GCC and Assembly language. Consider an example (dangeous) foo.s

Final Exam. Fall Semester 2015 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

JTSK Programming in C II C-Lab II. Lecture 3 & 4

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

C and Programming Basics

ANSI C Programming Simple Programs

The Stack & Procedures

Mechanisms in Procedures. CS429: Computer Organization and Architecture. x86-64 Stack. x86-64 Stack Pushing

Credits and Disclaimers

Introduction to Computer Science Midterm 3 Fall, Points

Machine-level Programs Procedure

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C++ Tutorial AM 225. Dan Fortunato

Final CSE 131B Spring 2004

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

AMCAT Automata Coding Sample Questions And Answers

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Dynamic memory allocation

Computer Science & Engineering 150A Problem Solving Using Computers

C: How to Program. Week /Apr/23

Why VC++ instead of Dev C++?

Procedures and the Call Stack

Machine-Level Programming III: Procedures

Princeton University Computer Science 217: Introduction to Programming Systems. Assembly Language: Function Calls

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

void P() {... y = Q(x); print(y); return; } ... int Q(int t) { int v[10];... return v[t]; } Computer Systems: A Programmer s Perspective

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Functions. Systems Programming Concepts

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Computer Systems Lecture 9

CSCI 171 Chapter Outlines

Lab 3. Pointers Programming Lab (Using C) XU Silei

OUTLINE. Review Functions Pointers Function calls Array Pointers Pointer Arrays Data Structures and dynamic Memory Function Pointers quicksort example

Credits and Disclaimers

Approximately a Final Exam CPSC 206

2. Numbers In, Numbers Out

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

C mini reference. 5 Binary numbers 12

Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition. Carnegie Mellon

CS 2505 Computer Organization I Test 2. Do not start the test until instructed to do so! printed

CS165 Computer Security. Understanding low-level program execution Oct 1 st, 2015

Overview of UE 101: Algorithms and Programming

Buffer overflows (a security interlude) Address space layout the stack discipline + C's lack of bounds-checking HUGE PROBLEM

C Program Structures

High Performance Programming Programming in C part 1

C++ Named Return Value Optimization

Machine-Level Programming V: Unions and Memory layout

Types. C Types. Floating Point. Derived. fractional part. no fractional part. Boolean Character Integer Real Imaginary Complex

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Credits and Disclaimers

Fundamentals of Programming Session 4

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CS 137 Part 9. Fibonacci, More on Tail Recursion, Map and Filter. November 22nd, 2017

Generation. representation to the machine

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Assembly Language: Function Calls

Compiling and Running a C Program in Unix

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

How Software Executes

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Memory Corruption Vulnerabilities, Part I

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Changelog. Assembly (part 1) logistics note: lab due times. last time: C hodgepodge

2. Numbers In, Numbers Out

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Subject: Fundamental of Computer Programming 2068

1 Number Representation(10 points)

Machine-Level Programming (2)

Corrections made in this version not seen in first lecture:

BSM540 Basics of C Language

Functions. Arash Rafiey. September 26, 2017

Multiple Choice Questions ( 1 mark)

How Software Executes

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

University of Washington

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Assembly Language II: Addressing Modes & Control Flow

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

ET156 Introduction to C Programming

Transcription:

Function Pointers

Memory layout int foo() { int b; } int main() { int a; foo(); } compile main:.lfb6: pushq %rbp.lcfi2: movq %rsp, %rbp.lcfi3: subq $32, %rsp.lcfi4: movl %edi, -20(%rbp) movq %rsi, -32(%rbp) movl $10, -4(%rbp) movl -4(%rbp), %edi call foo leave ret Program Stack foo: int b main: int a Heap main:.lfb6: pushq %rbp.lcfi2: movq %rsp, %rbp.lcfi3: subq $32, %rsp.lcfi4: movl %edi, -20(%rbp) movq %rsi, -32(%rbp) movl $10, -4(%rbp) movl -4(%rbp), %edi call foo leave ret

Functions as pointers Function code is stored in memory So a function should have an address The address of a function is a function pointer Function pointers can be passed as arguments to other functions or return from functions

Why do we need function Efficiency Pointers? Less # of if statements Runtime binding Determine sorting function based on type of data at run time Insertion sort for smaller data sets (n <100) Better algorithms for large data sets

Define a Function Pointer int (*funcpointer) (int, char, int); funcpointer is a variable name pointing to a function The extra parentheses around (*funcpointer) is needed

Using function pointers //assign an address to the function pointer int (*funcpointer) (int, char, int); int firstexample ( int a, char b, int c){ printf( Welcome to the first example ); return a+b+c; } funcpointer= firstexample; //assignment funcpointer=&firstexample; //alternative using address operator

Assign an address to a Function Pointer It is optional to use the address operator & infront of the function s name Similar to the fact that a pointer to the first element of an array is generated automatically when an array appears in an expression

Comparing Function Pointers Can use the (==) operator //comparing function pointers If (funcpointer == &firstexample) printf ( pointer points to firstexample );

Calling a function using a Function Pointer There are two alternatives // calling a function using function pointer int answer= funcpointer (7, A, 2 ); int answer=(* funcpointer) (7, A, 2 );

Arrays of Function Pointers C treats pointers to functions just like pointers to data therefore we can have arrays of pointers to functions This offers the possibility to select a function using an index

void (*file_cmd[]) (void) = { new_cmd, open_cmd, close_cmd, save_cmd, save_as_cmd, print_cmd, exit_cmd }; Compare the syntax with int a[]= { 1, 2, 3 }; If the user selects a command between 0 and 6, then we can subscript the file_cmd array to find out which function to call file_cmd[n]();

Trigonometric Functions // prints tables showing the values of cos,sin #include <math.h> #include <stdio.h> void tabulate(double (*f)(double), double first, double last, double incr); main() { double final, increment, initial; printf ( Enter initial value: ); scanf ( %lf, &initial); printf ( Enter final value: ); scanf (%lf, &final); printf ( Enter increment : ); scanf (%lf, &increment); Printf( \n x cos(x) \n ---------- -----------\n ); tabulate(cos, initial,final,increment); Printf( \n x sin (x) \n ---------- -----------\n ); tabulate(sin, initial,final,increment); } return 0;

Trigonometric Functions // when passed a pointer f prints a table showing the value of f void tabulate(double (*f) (double), double first, double last, double incr) { double x; int i, num_intervals; num_intervals = ceil ( (last -first) /incr ); for (i=0; i<=num_intervals; i++){ x= first +i * incr; printf( %10.5f %10.5f\n, x, (*f) (x)); } }

Enter initial value: 0 Enter final value:.5 Enter increment:.1 X cos(x) ---- -------- ----------- 0.00000 1.00000 0.10000 0.99500 0.20000 0.98007 0.30000 0.95534 0.40000 0.92106 0.50000 0.87758 X sin(x) ---- -------- ----------- 0.00000 0.00000 0.10000 0.09983 0.20000 0.19867 0.30000 0.29552 0.40000 0.38942 0.50000 0.47943

Sorting qsort will sort an array of elements. This is a wild function that uses a pointer to another function that performs the required comparisons. Library: stdlib.h Prototype: void qsort ( void *base, size_t num, size_t size, int (*comp_func) (const void *, const void *)) base is a pointer to the array to be sorted. This can be a pointer to any data type num The number of elements. size The element size. int (*comp_func)(const void *, const void *)) This is a pointer to a function.

Using qsort A A is an array of integers. Sort it using qsort with natural integer order Write the compare function: int intcomp(const void* a, const void* b);

Using qsort A Write the compare function to sort by alphabetical order int strcomp(const void* a, const void* b) { return strcmp( (const char*)a, (const char*)b); }

Sorting qsort thus maintains it's data type independence by giving the comparison responsibility to the user. The compare function must return integer values according to the comparison result: less than zero : if first value is less than the second value zero : if first value is equal to the second value greater than zero : if first value is greater than the second value The generic pointer type void * is used for the pointer arguments, any pointer can be cast to void * and back again without loss of information.

Conclusions Function pointers can be passed as arguments to other functions or return from functions Unfortunately, their cumbersome syntax baffles both novices and experienced programmers. C++ reduces the necessity of function pointers with classes and virtual functions