15-213 Recitation: C Review TA’s 2 Oct 2017.

Slides:



Advertisements
Similar presentations
Lecture 3 Some commonly used C programming tricks. The system command Project No. 1: A warm-up project.
Advertisements

Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Course Introduction Bryce Boe 2013/06/25 CS24, Summer 2013 C.
C Programming - Lecture 5
Buffer Overflow Exploits CS-480b Dick Steflik. What is a buffer overflow? Memory global static heap malloc( ), new Stack non-static local variabled value.
CSE 451 Section Autumn 2005 Richard Dunn Office hours: WTh 3:30-4:20 Allen 216 (or lab)
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
How to Write a.c File : Introduction to Computer Systems Recitation 6, Oct 1, 2012 Alexander Malyshev (amalyshe) Section A, 10:30a – 11:20p, WeH.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Cache Lab Implementation and Blocking
Cache Lab Implementation and Blocking
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
Chapter 6 Buffer Overflow. Buffer Overflow occurs when the program overwrites data outside the bounds of allocated memory It was one of the first exploited.
Stack and Heap Memory Stack resident variables include:
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Some Basics && GDB overview Ram Sheshadri –
CS 590 Programming Environments with UNIX. Computer Lab Account Course Homepage
CacheLab Recitation 7 10/8/2012. Outline Memory organization Caching – Different types of locality – Cache organization Cachelab – Tips (warnings, getopt,
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Overflow Examples 01/13/2012. ACKNOWLEDGEMENTS These slides where compiled from the Malware and Software Vulnerabilities class taught by Dr Cliff Zou.
Agenda Attack Lab C Exercises C Conventions C Debugging
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
(language, compilation and debugging) David 09/16/2011.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
RECITATION Cache Lab and C
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
COP 3275 – Character Strings Instructor: Diego Rivera-Gutierrez.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Homework Continue with K&R Chapter 5 –Skipping sections for now –Not covering section 5.12 Continue on HW5.
CSE 333 – SECTION 2 Memory Management. Questions, Comments, Concerns Do you have any? Exercises going ok? Lectures make sense? Homework 1 – START EARLY!
Memory-Related Perils and Pitfalls in C
Dynamic Allocation in C
Content Coverity Static Analysis Use cases of Coverity Examples
YongChul Kwon CSE451 Section 1: Spring 2006 YongChul Kwon
Recitation 5: Attack Lab
Stack and Heap Memory Stack resident variables include:
C Primer.
CSE 374 Programming Concepts & Tools
Recitation 6: C Review 30 Sept 2016.
Recitation: Bomb Lab _______________ 18 Sep 2017.
Valgrind Overview What is Valgrind?
Recitation: Attack Lab
CSE 303 Concepts and Tools for Software Development
Recitation: Bomb Lab _______________ 06 Feb 2017.
CS 537 Section 1 Programming in Unix and C
Checking Memory Management
Recitation: C Review TA’s 19 Feb 2018.
CSCI206 - Computer Organization & Programming
Terminos españoles de ingeneria de computacion.
Recitation: Attack Lab
Dynamic Memory Allocation
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Pointers.
File Handling.
Outline Defining and using Pointers Operations on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Introduction to Static Analyzer
Homework Continue with K&R Chapter 5 Skipping sections for now
C Programming - Lecture 5
Valgrind Overview What is Valgrind?
Dynamic Memory – A Review
15213 C Primer 17 September 2002.
Caches and Blocking 26th February 2018.
Format String Vulnerability
Presentation transcript:

15-213 Recitation: C Review TA’s 2 Oct 2017

Agenda Logistics Attack Lab Conclusion C Assessment C Programming Style C Exercise Cache Lab Overview Appendix: Valgrind Clang / LLVM Cache Structure

Logistics Attack Lab is due tomorrow at midnight! Come to office hours for help rtarget phase 3 is only worth 5 points 0.2% of your grade ≈ 0% of your grade Cache Lab will be released shortly thereafter!

Attack Lab Conclusion Don’t use functions vulnerable to buffer overflow (like gets) Use functions that allow you to specify buffer lengths: fgets instead of gets strncpy instead of strcpy strncat instead of strcat snprintf instead of sprint Use sscanf and fscanf with input lengths (%213s) Stack protection makes buffer overflow very hard… But very hard ≠ impossible!

C Assessment 3.5 Basic C Programming Questions Take some time to write down your answer for each question Don’t worry if you think these questions are hard… Come to the C Bootcamp (Check Piazza for time and location)

C Assessment: Question 1 Which lines have a problem and how can you fix it? 1 int main(int argc, char** argv) { 2 int *a = (int*) malloc(213 * sizeof(int)); 3 for (int i=0; i<213; i++) { 4 if (a[i] == 0) a[i]=i; 5 else a[i]=-i; 6 } 7 return 0; 8 }

C Assessment: Question 1 malloc can fail! 1 int main(int argc, char** argv) { 2 int *a = (int*) malloc(213 * sizeof(int)); if (a == NULL) return 0; 3 for (int i=0; i<213; i++) { 4 if (a[i] == 0) a[i]=i; 5 else a[i]=-i; 6 } 7 return 0; 8 }

C Assessment: Question 1 Allocated memory is not initialized! 1 int main(int argc, char** argv) { 2 int *a = (int*) calloc(213 * sizeof(int)); if (a == NULL) return 0; 3 for (int i=0; i<213; i++) { 4 if (a[i] == 0) a[i]=i; 5 else a[i]=-i; 6 } 7 return 0; 8 }

C Assessment: Question 1 Declaring variables inside a for loop requires -std=c99 1 int main(int argc, char** argv) { 2 int *a = (int*) calloc(213 * sizeof(int)); if (a == NULL) return 0; 3 for (int i=0; i<213; i++) { 4 if (a[i] == 0) a[i]=i; 5 else a[i]=-i; 6 } 7 return 0; 8 }

C Assessment: Question 1 All allocated memory must be freed! 1 int main(int argc, char** argv) { 2 int *a = (int*) calloc(213 * sizeof(int)); if (a == NULL) return 0; 3 for (int i=0; i<213; i++) { 4 if (a[i] == 0) a[i]=i; 5 else a[i]=-i; 6 } free(a); 7 return 0; 8 }

C Assessment: Question 2 What are the values of A and B? #define SUM(x, y) x + y int sum(int x, int y) { return x + y; } int A = SUM(2, 1) * 3; int B = sum(2, 1) * 3;

C Assessment: Question 2 What is wrong with our macro SUM? #define SUM(x, y) x + y int sum(int x, int y) { return x + y; } int A = SUM(2, 1) * 3; // A = 2 + 1 * 3 = 5!? int B = sum(2, 1) * 3; // B = 6

C Assessment: Question 2 Use parenthesis around result! #define SUM(x, y) (x + y) int sum(int x, int y) { return x + y; } int A = SUM(2, 1) * 3; // A = 6 int B = sum(2, 1) * 3; // B = 6

C Assessment: Question 2 Part B What are the values of A and B? #define MULT(x, y) (x * y) int mult(int x, int y) { return x * y; } int A = MULT(2, 0 + 1) * 3; int B = mult(2, 0 + 1) * 3;

C Assessment: Question 2 Part B What is wrong with our macro MULT? #define MULT(x, y) (x * y) int mult(int x, int y) { return x * y; } int A = MULT(2, 0 + 1) * 3; // A = (2 * 0 + 1) * 3 = 3?! int B = mult(2, 0 + 1) * 3; // B = 6

C Assessment: Question 2 Part B Use parenthesis around macro arguments (and result)! #define MULT(x, y) ((x) * (y)) int mult(int x, int y) { return x * y; } int A = MULT(2, 0 + 1) * 3; // A = ((2) * (0 + 1)) * 3 = 6 int B = mult(2, 0 + 1) * 3; // B = 6

C Assessment: Question 2 Macros are good for compile-time decisions Assert, requires, etc dbg_print Macros are not functions and should not be used interchangeably

C Assessment: Question 3 What lines make safe_int_malloc not so safe? 1 int *safe_int_malloc(int *pointer) { 2 pointer = malloc(sizeof(int)); 3 if (pointer == NULL) exit(-1); 4 return &pointer; 5 }

C Assessment: Question 3 pointer is a local copy of the pointer! 1 int *safe_int_malloc(int **pointer) { 2 *pointer = malloc(sizeof(int)); 3 if (pointer == NULL) exit(-1); 4 return &pointer; 5 }

C Assessment: Question 3 &pointer is a location on the stack in safe_int_malloc’s frame! 1 int **safe_int_malloc(int **pointer) { 2 *pointer = malloc(sizeof(int)); 3 if (pointer == NULL) exit(-1); 4 return pointer; 5 }

C Assessment Conclusion Did you answer every question correctly? If not… Come to the C Bootcamp (Check Piazza for time and location) Was the test so easy you were bored? If not… When in doubt… This will be very important for the rest of this class, so make sure you are comfortable with the material covered or come to the C Bootcamp!

C Programming Style Document your code with comments Check error and failure conditions Write modular code Use consistent formatting Avoid memory and file descriptor leaks Warning: Dr. Evil has returned to grade style on Cache Lab!  Refer to full 213 Style Guide: http://cs.cmu.edu/~213/codeStyle.html

C Exercise Learn to use getopt Extremely useful for Cache Lab Processes command line arguments Let’s write a Pythagorean Triples Solver! Pair up! Login to a shark machine $ wget http://cs.cmu.edu/~213/recitations/rec6.tar $ tar xvf rec6.tar $ cd rec6 But first, a simple getopt example… $ vim getopt-example.c

C Exercise: $ man 3 getopt int getopt(int argc, char * const argv[], const char *optstring); getopt returns -1 when done parsing optstring is string with command line arguments Characters followed by colon require arguments Find argument text in char *optarg getopt can’t find argument or finds illegal argument sets optarg to “?” Example: “abc:d:” a and b are boolean arguments (not followed by text) c and d are followed by text (found in char *optarg)

C Exercise: C Hints and Math Reminders 𝑎 2 + 𝑏 2 = 𝑐 2 ⇒𝑎= 𝑐 2 − 𝑏 2 ⇒𝑏= 𝑐 2 − 𝑎 2 ⇒𝑐= 𝑎 2 + 𝑏 2 ⇒ 3 2 + 4 2 = 5 2 String to float in C: #include <stdlib.h> float atof(const char *str); Square root in C: #include <math.h> float sqrt(float x);

Cache Lab Overview Programs exhibiting locality run a lot faster! Temporal Locality – same item referenced again Spatial Locality – nearby items referenced again Cache Lab’s Goal: Understand how L1, L2, … etc. caches work Optimize memory dependent code to minimize cache misses and evictions Noticeable increase in speed

If you get stuck… Reread the writeup Look at CS:APP Chapter 6 Review lecture notes (http://cs.cmu.edu/~213) Come to Office Hours (Sunday to Thursday, 5-9pm WH-5207) Post private question on Piazza man malloc, man valgrind, man gdb

Cache Lab Tips! Review cache and memory lectures Ask if you don’t understand something Start early, this can be a challenging lab! Don’t get discouraged! If you try something that doesn't work, take a well deserved break, and then try again Finally, Good luck on Cache Lab!

Appendix Valgrind Clang / LLVM Cache Structure

Appendix: Valgrind Tool used for debugging memory use Finds many potential memory leaks and double frees Shows heap usage over time Detects invalid memory reads and writes To learn more… man valgrind Finding memory leaks $ valgrind –leak-resolution=high –leak-check=full –show- reachable=yes –track-fds=yes ./myProgram arg1 arg2

Appendix: Clang / LLVM Clang is a (gcc equivalent) C compiler Support for code analyses and transformation Compiler will check you variable usage and declarations Compiler will create code recording all memory accesses to a file Useful for Cache Lab Part B (Matrix Transpose)

Appendix: Cache Structure