RECURSIVE FUNCTIONS ON STACK

Size: px
Start display at page:

Download "RECURSIVE FUNCTIONS ON STACK"

Transcription

1 Debugging with Visual Studio & GDB OCTOBER 31, 2015 BY CSC 342 FALL 2015 Prof. IZIDOR GERTNER

2 1 Table of contents 1. Objective... pg Overview... pg Microsoft s Visual Studio Debugger... pg Iterative Method... pg Recursive Method... pg GDB Debugger for Linux... pg Iterative Method... pg Recursive Method... pg Analysis... pg Conclusion... pg Appendix... pg. 31

3 2 1. Objective The objective of this laboratory is to understand how the stack works with recursive functions. We will do this by debugging a function in two different environments; Visual Studio and GDB. We take into consideration a simple function to calculate the factorial of a number. This is a very useful function to understand how the stack works on recursive functions by comparing it with a regular iterative function. The results of these laboratory will be summarized in a plot of the running time of each method versus the value of the number of which the factorial is to be calculated.

4 3 2. Overview Recursive functions are routines that call themselves. We use these type of functions to solve large problems by combining the solution of smaller sub-problems and since this kind of routine works by calling itself, it will eventually come to a sub-problem which it can solve without calling itself. This case is called the Base Case of the routine. In our case the base case is when the number that we are trying to calculate the factorial of reaches the value of 1. The function that is going to be used to achieve the goal of this laboratory is the Factorial function. The factorial of a number is defined by the symbol!, i.e. exclamation mark. Whenever we see a notation like x! we understand that we are talking about the factorial of number x. The factorial is the product of all the numbers between x and 1. We do not want to go beyond one because a multiplication with zero would result in zero no matter how large the number x is. Furthermore it is unnecessary to compute the factorial of negative numbers since we can simply negate the result to get the product of negative x for example. We use a simple fact of the factorial function to put it into a recursive form. Since the factorial of number x is the product of the numbers between x and 1, we can write: x! = x (x 1) (x 2) 1 It is trivial to see from the above definition of the factorial that x! can be rewritten as: x! = x (x 1)! and (x 1)! = (x 1) (x 2)! and so on Hence, we can use a recursive routine to solve sub-problems till we reach the base case. Recursive functions use call stack.

5 4 A call stack is composed of stack frames and a new frame is created each time the subroutine is called from the recursive function. The stack frame is used to store all the variables for one invocation of a routine. For the recursive factorial function we except the compiler to create a new stack frame for each call to the function. For very large numbers we expect to have a very large number of stack frames created by the compiler and this would mean using a lot of memory. The following picture illustrates what was stated above: Figure 1 Stack Frames for the Recursive Factorial Function

6 5 3. Microsoft s Visual Studio Debugger 3.1. Iterative Method In this part of the project we take into consideration the iterative method of the factorial function and debug it via the Visual Studio Debugger. Create a new project in Visual Studio and set it up as an Empty Function. Next, create two new files, the first one is the main function where the second file, factorial will be called from. The following figure shows the two functions to be created: Figure 2 Iterative Method Functions We compile and link these two functions together to make sure that we have we do not have any errors in our code. Then we start debugging. The following figure shows the state of the stack just before calling the factorial function from the main function:

7 6 Figure 3 Stack Frame of main We can see that the stack frame for the main function is created and we have a base pointer that contains the address 0x0043F874. Let s continue our debugging session by entering the factorial function. We expect the compiler to create a new stack frame for the function called and so the base pointer should point to the new base of the frame, which is a different address than that of the main function. Consider the following screenshot:

8 7 Figure 4 Iterative Factorial Function Stack We can see that our expectations are met and the address of the base pointer has changed. We now have a new stack frame with the necessary variables stored. In the above figure, the red square contains the address of the EBP pointer which now has a new value of 0x004F790. The blue square shows the location where the variable i is stored and currently has a value of 0x01, and the green circle shows the location of where the variable j is stored which has the value of 0x01 since the. Our final result will be stored in j. Let s observe the stack after the loop has completed all five iterations.

9 8 Figure 5 End of Iterative Function As we can see, the value of i at this point is 5, therefore the loop has finished iterating and the function will return the value of j which is stored in memory location 0x0043F788 and is 0x78. If we convert this value from Little Endian Notation and from hexadecimal to decimal notation we get the value of 120. After this the function will return to the last address in main before we jumped into the factorial function. We have achieved our goal and have the expected result in stack. We only created one frame and everything was done inside this frame by using the iterative method. Let s see how the stack behaves when we are dealing with a recursive function.

10 Recursive Method Consider the following functions that are used in Visual Studio to run the recursive method of the factorial function: Figure 6 Recursive Method Functions As we can see the way of coding the factorial function is different this time. We compile each of these two files separately and afterwards we link them together by clicking on the Build Solution option of Visual Studio. After we make sure that our program is correctly coded we procced to start a debugging session. We click on the Start with Debugging option and step over some instruction till we have the stack created for the main function and we are ready to jump into the recursive factorial function. The following screenshot shows the stack frame of the main function just before calling the recfactorial function:

11 10 Figure 7 Stack Frame of main Function We now have a stack frame for our main function. The base pointer, depicted by the red square in the figure, points to the address 0x001AFA84 which is the base of the main function frame. We can see that the variable n, shown inside the green square of value 0x05, is stored at location 0x001AFA7C and we have the variable result initialized to zero at location 0x001AFA70 which is contained within blue square. On the other hand, the purple square contains the address of the instruction that recursive factorial function will return after it has completed its task. We are ready to jump into the recursive factorial function. The following picture shows the stack frame for the recursive factorial function with parameter n = 5:

12 11 Figure 8 Recursive Stack Frame 1 We notice that for this frame we have a new base pointer, meaning that the compiler created a new stack frame. This new base pointer is indicated by the red square. The green square shows the location of variable n, which is below the base pointer. This is what we expected since this variable was pushed in stack before calling the recursive factorial function. The purple box contains the address of the return to main instruction which was also pushed in stack just before calling the function and therefore is below the base pointer. Let s call this Recursive Stack Frame 1 since it is the first one created by the compiler after the main function stack frame. Since the value of n in this function is not zero, then the function will call itself again with variable n = 4. Let s consider the following screenshots that show the stack for each call:

13 12 Figure 9 Recursive Stack Frame 2 Figure 10 Recursive Stack Frame 3

14 13 Figure 11 Recursive Stack Frame 4 Figure 12 Recursive Stack Frame 5

15 14 In the above screenshots we can see that the compiler creates different stack frames for each function call. This can be seen by checking the EBP for each time. In stack frame 2, the base pointer contains the address 0x001AF8BC. In the next frame, where the parameter n is 3 we have the base pointer address 0x001AF7E4. Stack frame 4 starts at address 0x001AF70C and finally the last stack frame, where n is 1 has the base pointer pointing to address 0x001AF634. These different addresses for the base pointer show that each function call creates a new stack frame for each function. This could be very costly when we want to find the factorial of a large number, therefore we must be very careful when to use the recursive method. The next call to the recursive factorial function will take the parameter n equal to zero, therefore it will stop at the comparison instruction. At this point, the number 1 will be returned to the caller, which will multiply this number by the current value of n. The Stack Frames return their values to the previous frame, which called them, starting from the innermost frame and end up returning the final value to the main function which will assign it to the variable result. The following diagram shows how the Stack Frames work with each other:

16 15 Graph 1 Stack Frames of the Recursive Factorial After these operations are completed and the compiler has cleared all the Stack Frames that are not going to be used anymore, we return to the main function to assign the value of 120 to the variable result. Let s see the main stack frame after the return:

17 16 Figure 13 Stack Frame of Main Function As we can see in the red square, the base pointer is again pointing to the starting address that is 0x001AFA84. At location 0x001AFA7C, shown by the green square, we still have the value of n, which is 5. Finally we can see the result that we were expecting is now set to 0x78 at location 0x001AFA70 which is depicted by the blue square. We convert this value from Little Endian notation and then from hexadecimal notation to get the decimal value of it, which is 120 and we can conclude that the function has worked correctly. In terms of efficiency, the compiler had to create 5 different stack frames for each function call to the recursive routine and this might become very costly when dealing with very large integers. We have finished studying the behavior of the stack when dealing with recursive functions in Visual Studio. Now we are going to do the same analysis on a Linux platform.

18 17 4. GDB Debugger for Linux 4.1. Iterative Method We repeat the same experiment using another platform. This time we analyze the stack using a Linux operating system with 64-bit architecture. For this part we use the GCC compiler and the GDB debugger. The following figure shows the stack frame of the main function as soon as we run the program: Figure 14 Stack Frame of Main Function This is the disassembly window of our function. In the red square are shown the base pointer, the stack pointer and the current frames. The current frames are shown by using the command

19 18 info stack from GDB. This is a very interesting option because we can visualize better how many stack frames are created at this point of the program. The next thing to do is to step into the iterative factorial function, disassemble and check the stack. The following screenshot shows the stack at the moment of the first iteration of the loop: Figure 15 Stack Frame of Factorial Function (Part 1) As we can see the base pointer has changed and now points to a new address 0x7FFFFFFFDF60 which is different from the base pointer of the main function. This means that the compiler has created a new frame for the factorial function. Also, from the info stack command we can see that we now have two frames for our program. The frame that we are currently is depicted by #0 and the frame where we will return after this function has

20 19 completed its task is frame #1. The stack works as a LIFO (Last In First Out) data structure. This means that the last frame to be created will be the first one to return. The next screenshot shows the state of the stack after the last iteration of the loop: Figure 16 Stack Frame of Factorial Function (Part 2) At this point of the program we have finished iterating through the loop. The value of the variable j is the final value that we are looking for. We can check the value of j in two ways, one way is to look at the contents of the memory address where j is stored and the other way is to simply print out the value of j using the print option of GDB. As we can see from the red squares in the screenshot, the value of j is now 120. Notice that we still have two stack frames. This is because we have not returned to the main function yet, but since we are done with the iterations we can return. The following figure shows the state of the stack for the main function when we return from the factorial function:

21 20 Figure 17 Stack Frame of Main Function after Returning As we can see the base pointer points to address 0x7FFFFFFFDF80 again and the value of the result is located in the stack at memory address 0x7FFFFFFFDF78. We can say that our function has worked correctly. We can continue our study of the stack by using the recursive method now.

22 Recursive Method For this method, we use the same function as we used in Visual Studio. The following screenshot shows the stack of the main function as soon as we enter the program: Figure 18 Stack Frame of Main Function In this case the base pointer points to address 0x7FFFFFFFDF40 and from the info stack command we can see that we have only one stack frame created so far. Let s step into the recursive factorial function to see how the stack behaves:

23 22 Figure 19 Recursive Factorial Stack Frame 5 We can see from the figure that the base pointer now points to another address and therefore we know that the compiler has created a new stack frame. We can confirm this by the info stack command which gives us two stack frames. The innermost frame is the frame for the recfactorial function which takes as argument n = 5. Let s consider all the stack frames created for the Recursive function now. The following pictures show the frames created each time the recursive function calls itself:

24 23 Figure 20 Recursive Factorial Stack Frame 4 Figure 21 Recursive Factorial Stack Frame 3

25 24 Figure 22 Recursive Factorial Stack Frame 2 Figure 23 Recursive Factorial Stack Frame 1

26 25 We can see that the stack frames are different for each call of the recursive factorial. In total we have six frames created at the end of the recursion. Five of these frames are created by the recursive factorial function and the last one is the main function stack frame. In each of the above pictures the stack frames are inside the red square. The last recursive call will take n = 0 as an argument therefore it will return 1 to the previous stack frame which will multiply it by its current n. The same procedure will be executed as when we were working with Visual Studio. The frames will be popped one by one till we get to the main function and assign the final value to the variable result. The following two screenshots show how the frames disappear when we keep stepping into our program: Figure 24 Returning Stack Frames (Part 1)

27 26 Figure 24 Returning Stack Frames (Part 2) As we can see, at the last step we are left with only one stack frame, the one that we started with, i.e. the main function stack frame. For every step we take the current value of n is returned from the current frame and then it is multiplied with the value of n that was on the previous frame. As we said before, the LIFO property of the stack is not lost. Let s make one more step and check the state of the main function stack frame after we return from all the recursive calls. The following screenshot shows the result:

28 27 Figure 25 Stack Frame of Main Function after Returning As we can see we are back where we started, at the main function frame with base pointer at memory address 0x7FFFFFFFDF40. We can see that the value of the variable result is stored in memory location 0x7FFFFFFFDF38 and it is equal to 120. This means that the recursive factorial function has finished correctly and we have the value that we were looking for.

29 28 5. Analysis To analyze the performance of the recursive method versus the performance of the iterative method we use the QueryPerformanceCounter function to measure the running time of each function. The following table shows the running time of each function for different values of n, i.e. the number which we want to calculate the factorial: n Iterative (seconds) Recursive (seconds) , , , ,00, Table 1 Iterative vs Recursive Running Time As we can see, there is running time of zero for very large values of n in the recursive method. This means that there is not enough memory to create the necessary stack frames for the 100,000 recursions and the compiler generates and error: Process is terminated due to StackOverflowException. In order to visualize better the performance of these two functions we plot the running times for each of the values of n in a graph to see how they behave. The following graph shows the plot of the running time vs. the size of n:

30 Time (Seconds) 29 Iterative vs. Recursive Function Calls Iterative Recursive ^1 10^2 10^3 10^4 10^5 10^6 n Graph 1 Iterative vs Recursive Running Time It is obvious that the recursive method is much faster than the iterative method for some range of values of n, but after a certain value we cannot use the recursive method anymore because it would result in Stack Overflow which would terminate our program immediately.

31 30 6. Conclusion In this laboratory we studied the behavior of the stack when we worked with recursive functions and compared it to the iterative methods. The function chosen to be analyzed was the factorial one. We calculated the factorial of the integer 5. The iterative method created only one stack frame for the function and it worked within that frame. The variables were stored in the same frame and were overwritten by the new value assigned to the final result. On the other hand the recursive functions force the compiler to create a new frame every time the sub-routine is called. This method could be very expensive as the number to be calculated gets bigger. Therefore we need to be careful when to use the recursive methods because we might be better off by using a simple iterative loop.

32 31 7. Appendix main.cpp int factorial(int n); void main(){ int n = 5; factorial(5); } factorial.cpp int factorial(int n){ int j = 1; for(int i = 1; i <= n; i++) j *= i; return j; } recfactorial.cpp int recfactorial(int n) { if (n == 0) return 1; } return n * recfactorial(n - 1);

CS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri

CS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri CS356: Discussion #6 Assembly Procedures and Arrays Marco Paolieri (paolieri@usc.edu) Procedures Functions are a key abstraction in software They break down a problem into subproblems. Reusable functionality:

More information

Subprograms, Subroutines, and Functions

Subprograms, Subroutines, and Functions Subprograms, Subroutines, and Functions Subprograms are also called subroutines, functions, procedures and methods. A function is just a subprogram that returns a value; say Y = SIN(X). In general, the

More information

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of

More information

CNIT 127: Exploit Development. Ch 2: Stack Overflows in Linux

CNIT 127: Exploit Development. Ch 2: Stack Overflows in Linux CNIT 127: Exploit Development Ch 2: Stack Overflows in Linux Stack-based Buffer Overflows Most popular and best understood exploitation method Aleph One's "Smashing the Stack for Fun and Profit" (1996)

More information

CSC 2400: Computer Systems. Using the Stack for Function Calls

CSC 2400: Computer Systems. Using the Stack for Function Calls CSC 24: Computer Systems Using the Stack for Function Calls Lecture Goals Challenges of supporting functions! Providing information for the called function Function arguments and local variables! Allowing

More information

Systems I. Machine-Level Programming V: Procedures

Systems I. Machine-Level Programming V: Procedures Systems I Machine-Level Programming V: Procedures Topics abstraction and implementation IA32 stack discipline Procedural Memory Usage void swap(int *xp, int *yp) int t0 = *xp; int t1 = *yp; *xp = t1; *yp

More information

Part 7. Stacks. Stack. Stack. Examples of Stacks. Stack Operation: Push. Piles of Data. The Stack

Part 7. Stacks. Stack. Stack. Examples of Stacks. Stack Operation: Push. Piles of Data. The Stack Part 7 Stacks The Stack Piles of Data Stack Stack A stack is an abstract data structure that stores objects Based on the concept of a stack of items like a stack of dishes Data can only be added to or

More information

CSC 8400: Computer Systems. Using the Stack for Function Calls

CSC 8400: Computer Systems. Using the Stack for Function Calls CSC 84: Computer Systems Using the Stack for Function Calls Lecture Goals Challenges of supporting functions! Providing information for the called function Function arguments and local variables! Allowing

More information

Buffer Overflow Attack (AskCypert CLaaS)

Buffer Overflow Attack (AskCypert CLaaS) Buffer Overflow Attack (AskCypert CLaaS) ---------------------- BufferOverflow.c code 1. int main(int arg c, char** argv) 2. { 3. char name[64]; 4. printf( Addr;%p\n, name); 5. strcpy(name, argv[1]); 6.

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

Chapter 7 Subroutines. Richard P. Paul, SPARC Architecture, Assembly Language Programming, and C

Chapter 7 Subroutines. Richard P. Paul, SPARC Architecture, Assembly Language Programming, and C Chapter 7 Subroutines Richard P. Paul, SPARC Architecture, Assembly Language Programming, and C 2 Subroutines Subroutines allow us to either to repeat a computation or to repeat the computation with different

More information

Stack overflow exploitation

Stack overflow exploitation Stack overflow exploitation In order to illustrate how the stack overflow exploitation goes I m going to use the following c code: #include #include #include static void

More information

Procedure-Calling Conventions October 30

Procedure-Calling Conventions October 30 Procedure-Calling Conventions October 30 CSC201 Section 002 Fall, 2000 Saving registers Registers are inevitably used by subroutines; changes their! Registers have global scope; calling procedures also

More information

Chapter 2A Instructions: Language of the Computer

Chapter 2A Instructions: Language of the Computer Chapter 2A Instructions: Language of the Computer Copyright 2009 Elsevier, Inc. All rights reserved. Instruction Set The repertoire of instructions of a computer Different computers have different instruction

More information

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1 COMP 202 Recursion CONTENTS: Recursion COMP 202 - Recursion 1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself COMP 202 - Recursion

More information

CSC 2400: Computer Systems. Using the Stack for Function Calls

CSC 2400: Computer Systems. Using the Stack for Function Calls CSC 24: Computer Systems Using the Stack for Function Calls Lecture Goals Challenges of supporting functions! Providing information for the called function Function arguments and local variables! Allowing

More information

1 Dynamic Memory continued: Memory Leaks

1 Dynamic Memory continued: Memory Leaks CS104: Data Structures and Object-Oriented Design (Fall 2013) September 3, 2013: Dynamic Memory, continued; A Refresher on Recursion Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we continue

More information

MARS MIDI Player - Technical Design Document

MARS MIDI Player - Technical Design Document MARS MIDI Player - Technical Design Document Convert from *.mid to *.luke 1. Get a selection of MIDI files you wish to play 2. Open up MIDI to Text v17.exe and load in the MIDI files you want, making sure

More information

Source level debugging. October 18, 2016

Source level debugging. October 18, 2016 Source level debugging October 18, 2016 Source level debugging Source debugging is a nice tool for debugging execution problems; it can be particularly useful when working with crashed programs that leave

More information

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1 MPATE-GE 2618: C Programming for Music Technology Unit 4.1 Memory Memory in the computer can be thought of as a long string of consecutive bytes. Each byte has a corresponding address. When we declare

More information

(Refer Slide Time: 00:51)

(Refer Slide Time: 00:51) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 10 E Lecture 24 Content Example: factorial

More information

143A: Principles of Operating Systems. Lecture 4: Calling conventions. Anton Burtsev October, 2017

143A: Principles of Operating Systems. Lecture 4: Calling conventions. Anton Burtsev October, 2017 143A: Principles of Operating Systems Lecture 4: Calling conventions Anton Burtsev October, 2017 Recap from last time Stack and procedure calls What is stack? Stack It's just a region of memory Pointed

More information

CSC 2400: Computing Systems. X86 Assembly: Function Calls"

CSC 2400: Computing Systems. X86 Assembly: Function Calls CSC 24: Computing Systems X86 Assembly: Function Calls" 1 Lecture Goals! Challenges of supporting functions" Providing information for the called function" Function arguments and local variables" Allowing

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 6: Recursive Functions. C Pre-processor. Cristina Nita-Rotaru Lecture 6/ Fall 2013 1 Functions: extern and static Functions can be used before they are declared static for

More information

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. Refresher When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. i.e. char *ptr1 = malloc(1); ptr1 + 1; // adds 1 to pointer

More information

Introduction to Scientific Computing

Introduction to Scientific Computing Introduction to Scientific Computing Dr Hanno Rein Last updated: October 12, 2018 1 Computers A computer is a machine which can perform a set of calculations. The purpose of this course is to give you

More information

ECE251: Tuesday September 11

ECE251: Tuesday September 11 ECE251: Tuesday September 11 Finish Branch related instructions Stack Subroutines Note: Lab 3 is a 2 week lab, starting this week and covers the Stack and Subroutines. Labs: Lab #2 is due this week. Lab

More information

143A: Principles of Operating Systems. Lecture 5: Calling conventions. Anton Burtsev January, 2017

143A: Principles of Operating Systems. Lecture 5: Calling conventions. Anton Burtsev January, 2017 143A: Principles of Operating Systems Lecture 5: Calling conventions Anton Burtsev January, 2017 Stack and procedure calls Stack Main purpose: Store the return address for the current procedure Caller

More information

Lab 4 : MIPS Function Calls

Lab 4 : MIPS Function Calls Lab 4 : MIPS Function Calls Name: Sign the following statement: On my honor, as an Aggie, I have neither given nor received unauthorized aid on this academic work 1 Objective The objective of this lab

More information

Laboratory Assignment #4 Debugging in Eclipse CDT 1

Laboratory Assignment #4 Debugging in Eclipse CDT 1 Lab 4 (10 points) November 20, 2013 CS-2301, System Programming for Non-majors, B-term 2013 Objective Laboratory Assignment #4 Debugging in Eclipse CDT 1 Due: at 11:59 pm on the day of your lab session

More information

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution 1. (40 points) Write the following subroutine in x86 assembly: Recall that: int f(int v1, int v2, int v3) { int x = v1 + v2; urn (x + v3) * (x v3); Subroutine arguments are passed on the stack, and can

More information

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5 Jackson State University Department of Computer Science CSC 439-01/539-02 Advanced Information Security Spring 2013 Lab Project # 5 Use of GNU Debugger (GDB) for Reverse Engineering of C Programs in a

More information

CSC 2400: Computing Systems. X86 Assembly: Function Calls

CSC 2400: Computing Systems. X86 Assembly: Function Calls CSC 24: Computing Systems X86 Assembly: Function Calls 1 Lecture Goals Challenges of supporting functions Providing information for the called function Function arguments and local variables Allowing the

More information

ECE251: Tuesday September 12

ECE251: Tuesday September 12 ECE251: Tuesday September 12 Finish Branch related instructions Stack Subroutines Note: Lab 3 is a 2 week lab, starting this week and covers the Stack and Subroutines. Labs: Lab #2 is due this week. Lab

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #34 Function with pointer Argument (Refer Slide Time: 00:05) So, here is the stuff that we have seen about pointers.

More information

(Refer Slide Time: 00:26)

(Refer Slide Time: 00:26) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements

More information

Programming Studio #9 ECE 190

Programming Studio #9 ECE 190 Programming Studio #9 ECE 190 Programming Studio #9 Concepts: Functions review 2D Arrays GDB Announcements EXAM 3 CONFLICT REQUESTS, ON COMPASS, DUE THIS MONDAY 5PM. NO EXTENSIONS, NO EXCEPTIONS. Functions

More information

Embedded Systems - FS 2018

Embedded Systems - FS 2018 Institut für Technische Informatik und Kommunikationsnetze Prof. L. Thiele Embedded Systems - FS 2018 Lab 0 Date : 28.2.2018 Prelab Filling the gaps Goals of this Lab You are expected to be already familiar

More information

SRC Assembly Language Programming - III

SRC Assembly Language Programming - III Computer Architecture Laboratory SRC Assembly Language Programming - III Goals: a) Learn assembly language subroutine methodology b) Write a subroutine in SRC assembler 1. As a group we will develop a

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!

More information

Motivation. Compiler. Our ultimate goal: Hack code. Jack code (example) Translate high-level programs into executable code. return; } } return

Motivation. Compiler. Our ultimate goal: Hack code. Jack code (example) Translate high-level programs into executable code. return; } } return Motivation Jack code (example) class class Main Main { { static static int int x; x; function function void void main() main() { { Inputs Inputs and and multiplies multiplies two two numbers numbers var

More information

Introduction to C/C++ Programming

Introduction to C/C++ Programming Chapter 1 Introduction to C/C++ Programming This book is about learning numerical programming skill and the software development process. Therefore, it requires a lot of hands-on programming exercises.

More information

Problem with Scanning an Infix Expression

Problem with Scanning an Infix Expression Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix

More information

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

238P: Operating Systems. Lecture 3: Calling conventions. Anton Burtsev October, 2018

238P: Operating Systems. Lecture 3: Calling conventions. Anton Burtsev October, 2018 238P: Operating Systems Lecture 3: Calling conventions Anton Burtsev October, 2018 What does CPU do internally? (Remember Lecture 01 - Introduction?) CPU execution loop CPU repeatedly reads instructions

More information

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5 What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion

More information

CSE 230 Intermediate Programming in C and C++ Functions

CSE 230 Intermediate Programming in C and C++ Functions CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions

More information

Using a debugger. Segmentation fault? GDB to the rescue!

Using a debugger. Segmentation fault? GDB to the rescue! Using a debugger Segmentation fault? GDB to the rescue! But first... Let's talk about the quiz Let's talk about the previous homework assignment Let's talk about the current homework assignment K findkey(v

More information

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion Today s video will talk about an important concept in computer science which is

More information

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic Review from Letctures 3 & 4 C++ class syntax, designing classes, classes vs. structs; Passing comparison functions to

More information

After completing this appendix, you will be able to:

After completing this appendix, you will be able to: 1418835463_AppendixA.qxd 5/22/06 02:31 PM Page 879 A P P E N D I X A A DEBUGGING After completing this appendix, you will be able to: Describe the types of programming errors Trace statement execution

More information

Computer Architecture and System Software Lecture 06: Assembly Language Programming

Computer Architecture and System Software Lecture 06: Assembly Language Programming Computer Architecture and System Software Lecture 06: Assembly Language Programming Instructor: Rob Bergen Applied Computer Science University of Winnipeg Announcements Assignment 3 due thursday Midterm

More information

Programming and Data Structures in C Instruction for students

Programming and Data Structures in C Instruction for students Programming and Data Structures in C Instruction for students Adam Piotrowski Dariusz Makowski Wojciech Sankowski 11 kwietnia 2016 General rules When writing programs please note that: Program must be

More information

IDE: Integrated Development Environment

IDE: Integrated Development Environment Name: Student ID: Lab Instructor: Borja Sotomayor Do not write in this area 1 2 3 TOTAL Maximum possible points: 30 One of the goals of this lab is to introduce the Eclipse IDE, a software environment

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 9 (Part II) Recursion MOUNA KACEM Recursion: General Overview 2 Recursion in Algorithms Recursion is the use of recursive algorithms to solve a problem A recursive algorithm

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char

More information

Buffer-Overflow Attacks on the Stack

Buffer-Overflow Attacks on the Stack Computer Systems Buffer-Overflow Attacks on the Stack Introduction A buffer overflow occurs when a program, while writing data to a buffer, overruns the buffer's boundary and overwrites memory in adjacent

More information

Offensive Security My First Buffer Overflow: Tutorial

Offensive Security My First Buffer Overflow: Tutorial Offensive Security My First Buffer Overflow: Tutorial César Bernardini University of Trento cesar.bernardini@unitn.it October 12, 2015 2 Cesar Bernardini Postdoctoral Fellow at UNITN PhD Student at INRIA-LORIA

More information

Software Development. Modular Design and Algorithm Analysis

Software Development. Modular Design and Algorithm Analysis Software Development Modular Design and Algorithm Analysis Precondition and Postcondition To create a good algorithm, a programmer must be able to analyse a precondition (starting state) and a postcondition

More information

Run-Time Data Structures

Run-Time Data Structures Run-Time Data Structures Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers, it is used for:

More information

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 1. Do a page check: you should have 8 pages including this cover sheet. 2. You have 50 minutes

More information

Some Basic Concepts EL6483. Spring EL6483 Some Basic Concepts Spring / 22

Some Basic Concepts EL6483. Spring EL6483 Some Basic Concepts Spring / 22 Some Basic Concepts EL6483 Spring 2016 EL6483 Some Basic Concepts Spring 2016 1 / 22 Embedded systems Embedded systems are rather ubiquitous these days (and increasing rapidly). By some estimates, there

More information

Today's Topics. CISC 458 Winter J.R. Cordy

Today's Topics. CISC 458 Winter J.R. Cordy Today's Topics Last Time Semantics - the meaning of program structures Stack model of expression evaluation, the Expression Stack (ES) Stack model of automatic storage, the Run Stack (RS) Today Managing

More information

Rui Wang, Assistant professor Dept. of Information and Communication Tongji University.

Rui Wang, Assistant professor Dept. of Information and Communication Tongji University. Instructions: ti Language of the Computer Rui Wang, Assistant professor Dept. of Information and Communication Tongji University it Email: ruiwang@tongji.edu.cn Computer Hierarchy Levels Language understood

More information

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking Review for Test 2 (Chapter 6-10) Chapter 6: Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B.

More information

CSE Lecture In Class Example Handout

CSE Lecture In Class Example Handout CSE 30321 Lecture 07-09 In Class Example Handout Part A: A Simple, MIPS-based Procedure: Swap Procedure Example: Let s write the MIPS code for the following statement (and function call): if (A[i] > A

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Functions in MIPS. Functions in MIPS 1

Functions in MIPS. Functions in MIPS 1 Functions in MIPS We ll talk about the 3 steps in handling function calls: 1. The program s flow of control must be changed. 2. Arguments and return values are passed back and forth. 3. Local variables

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Project 3: RPN Calculator

Project 3: RPN Calculator ECE267 @ UIC, Spring 2012, Wenjing Rao Project 3: RPN Calculator What to do: Ask the user to input a string of expression in RPN form (+ - * / ), use a stack to evaluate the result and display the result

More information

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

Announcements. Assignment 2 due next class in CSIL assignment boxes

Announcements. Assignment 2 due next class in CSIL assignment boxes Announcements Assignment 2 due next class in CSIL assignment boxes Call Stacks + On Writing Good Code Jan. 21 Lecture 8 Today: Function Call Stack Recursion Good Coding Principles Stacks - a Brief Introduction

More information

Implementing Procedure Calls

Implementing Procedure Calls 1 / 39 Implementing Procedure Calls February 18 22, 2013 2 / 39 Outline Intro to procedure calls Caller vs. callee Procedure call basics Calling conventions The stack Interacting with the stack Structure

More information

COMP2611: Computer Organization MIPS function and recursion

COMP2611: Computer Organization MIPS function and recursion COMP2611 Fall2015 COMP2611: Computer Organization MIPS function and recursion Overview 2 You will learn the following in this lab: how to use MIPS functions in a program; the concept of recursion; how

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 10 Recursion and Search MOUNA KACEM mouna@cs.wisc.edu Spring 2019 Recursion: General Overview 2 Recursion in Algorithms Recursion is the use of recursive algorithms to

More information

Introduction to C. Why C? Difference between Python and C C compiler stages Basic syntax in C

Introduction to C. Why C? Difference between Python and C C compiler stages Basic syntax in C Final Review CS304 Introduction to C Why C? Difference between Python and C C compiler stages Basic syntax in C Pointers What is a pointer? declaration, &, dereference... Pointer & dynamic memory allocation

More information

Buffer-Overflow Attacks on the Stack

Buffer-Overflow Attacks on the Stack Computer Systems Buffer-Overflow Attacks on the Stack Introduction A buffer overflow occurs when a program, while writing data to a buffer, overruns the buffer's boundary and overwrites memory in adjacent

More information

Fun facts about recursion

Fun facts about recursion Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop

More information

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

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011 Functions in C Lecture Topics Introduction to using functions in C Syntax Examples Memory allocation for variables Lecture materials Textbook 14.1-14.2, 12.5 Homework Machine problem MP3.2 due March 18,

More information

ECE 190 Midterm Exam 3 Spring 2011

ECE 190 Midterm Exam 3 Spring 2011 ECE 190 Midterm Exam 3 Spring 2011 Practice Exam Notes: This exam will consist entirely of five programming problems. Each problem will be graded separately. We will provide skeleton codes for each problem.

More information

Call Stacks + On Writing Good Code

Call Stacks + On Writing Good Code Call Stacks + On Writing Good Code Lecture 8 Today: Function Call Stack Recursion Good Coding Principles Stacks - a Brief Introduction A stack is an ordered collection of items, to which you may insert

More information

Lab 10: Introduction to x86 Assembly

Lab 10: Introduction to x86 Assembly CS342 Computer Security Handout # 8 Prof. Lyn Turbak Wednesday, Nov. 07, 2012 Wellesley College Revised Nov. 09, 2012 Lab 10: Introduction to x86 Assembly Revisions: Nov. 9 The sos O3.s file on p. 10 was

More information

Computer Organization & Assembly Language Programming (CSE 2312)

Computer Organization & Assembly Language Programming (CSE 2312) Computer Organization & Assembly Language Programming (CSE 2312) Lecture 15: Running ARM Programs in QEMU and Debugging with gdb Taylor Johnson Announcements and Outline Homework 5 due Thursday Midterm

More information

UNIT-II. Part-2: CENTRAL PROCESSING UNIT

UNIT-II. Part-2: CENTRAL PROCESSING UNIT Page1 UNIT-II Part-2: CENTRAL PROCESSING UNIT Stack Organization Instruction Formats Addressing Modes Data Transfer And Manipulation Program Control Reduced Instruction Set Computer (RISC) Introduction:

More information

Lecture 7: Examples, MARS, Arithmetic

Lecture 7: Examples, MARS, Arithmetic Lecture 7: Examples, MARS, Arithmetic Today s topics: More examples MARS intro Numerical representations 1 Dealing with Characters Instructions are also provided to deal with byte-sized and half-word quantities:

More information

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion. Notes - Recursion So far we have only learned how to solve problems iteratively using loops. We will now learn how to solve problems recursively by having a method call itself. A geeky definition of recursion

More information

Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9

Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9 Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline More on MIPS Calling Convention Functions calling functions

More information

CMPSCI 187: Programming With Data Structures. Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012

CMPSCI 187: Programming With Data Structures. Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012 CMPSCI 187: Programming With Data Structures Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012 Thinking About Recursion Review of the Grid Class Recursion on Linked Structures

More information

Algorithm. An algorithm is a computational process for solving a problem. computational: a computer must be able to perform the steps of the process

Algorithm. An algorithm is a computational process for solving a problem. computational: a computer must be able to perform the steps of the process Algorithm An algorithm is a computational process for solving a problem. computational: a computer must be able to perform the steps of the process This concept was formalized by Alan Turing and Alonzo

More information

hardware interrupts software interrupts

hardware interrupts software interrupts CS 5212Operating Systems wk 4 Interrupts An interrupt is a signal received by the CPU that causes a temporary halt in the execution of a program while some other task is performed. Interrupts may be generated

More information

Run-time Environment

Run-time Environment Run-time Environment Prof. James L. Frankel Harvard University Version of 3:08 PM 20-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Storage Organization Automatic objects are

More information

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers? Review for Final (Chapter 6 13, 15) 6. Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B. To

More information

Buffer Overflow Attacks

Buffer Overflow Attacks CS- Spring Buffer Overflow Attacks Computer Systems..-, CS- Spring Hacking Roots in phone phreaking White Hat vs Gray Hat vs Black Hat Over % of Modern Software Development is Black Hat! Tip the balance:

More information

Single-Cycle CPU VITO KLAUDIO CSC343 FALL 2015 PROF. IZIDOR GERTNER

Single-Cycle CPU VITO KLAUDIO CSC343 FALL 2015 PROF. IZIDOR GERTNER Single-Cycle CPU CSC343 FALL 2015 PROF. IZIDOR GERTNER 1 Single-Cycle CPU Table of contents 1. Objective... pg. 2 2. Functionality... pg. 3 2.1 Part I (ADD/SUB)... pg. 7 2.2 Part II (ORI & BITWISE OPERATIONS)...

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

CSE 214 Computer Science II Recursion

CSE 214 Computer Science II Recursion CSE 214 Computer Science II Recursion Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction Basic design technique

More information

Computer Systems Lecture 9

Computer Systems Lecture 9 Computer Systems Lecture 9 CPU Registers in x86 CPU status flags EFLAG: The Flag register holds the CPU status flags The status flags are separate bits in EFLAG where information on important conditions

More information

NCS 301 DATA STRUCTURE USING C

NCS 301 DATA STRUCTURE USING C NCS 301 DATA STRUCTURE USING C Unit-1 Part-2 Recursion Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncs301ds.wordpress.com Introduction Recursion is defined as defining

More information

CS 161 Computer Security

CS 161 Computer Security Wagner Spring 2014 CS 161 Computer Security 1/27 Reasoning About Code Often functions make certain assumptions about their arguments, and it is the caller s responsibility to make sure those assumptions

More information