15-213 Recitation 6: C Review 30 Sept 2016.

Slides:



Advertisements
Similar presentations
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Advertisements

C Programming - Lecture 5
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Unix Process Environment. main Function A C program starts execution with a function called main. The prototype for the main function is: int main (int.
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.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
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,
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
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.
(language, compilation and debugging) David 09/16/2011.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
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
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
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.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
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
Recitation: C Review TA’s 2 Oct 2017.
Dynamic Allocation in C
Content Coverity Static Analysis Use cases of Coverity Examples
Recitation 5: Attack Lab
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 6 CS 3370 – C++ Functions.
5.13 Recursion Recursive functions Functions that call themselves
C Primer.
CSE 374 Programming Concepts & Tools
Sorting Tutorial Using C On Linux.
A bit of C programming Lecture 3 Uli Raich.
Recitation: Bomb Lab _______________ 18 Sep 2017.
Valgrind Overview What is Valgrind?
Recitation: Attack Lab
COSC 220 Computer Science II
CSE 303 Concepts and Tools for Software Development
Recitation 11: More Malloc Lab
Recitation: Bomb Lab _______________ 06 Feb 2017.
Workshop in Nihzny Novgorod State University Activity Report
Checking Memory Management
C Basics.
Dynamic Memory Allocation
Recitation: C Review TA’s 19 Feb 2018.
Caches and Blocking 8 October 2018.
Recitation 11: More Malloc Lab
Recitation 10: Malloc Lab
Terminos españoles de ingeneria de computacion.
Recitation: Attack Lab
Recitation 11: More Malloc Lab
Dynamic Memory Allocation
Memory Allocation CS 217.
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
C Programming - Lecture 5
Valgrind Overview What is Valgrind?
Dynamic Memory – A Review
Makefiles, GDB, Valgrind
15213 C Primer 17 September 2002.
Caches and Blocking 26th February 2018.
SPL – PS2 C++ Memory Handling.
Introduction to C CS 3410.
Presentation transcript:

15-213 Recitation 6: C Review 30 Sept 2016

Agenda Reminders Lessons from Attack Lab C Assessment Programming Style Cache Lab Overview Appendix: valgrind Appendix: Clang / LLVM

Reminders Attack Lab is due tomorrow! “But if you wait until the last minute, it only takes a minute!” - NOT! Cache Lab will be released tomorrow! Image credit: pixabay.com

Lessons from Attack Lab Never, ever use gets use fgets instead if you need that functionality Use functions that pass an explicit buffer length if possible strncpy/strncat instead of strcpy/strcat, snprintf instead of sprintf Limit scanf/fscanf input lengths with %123s Or use a function that dynamically allocates a large-enough buffer asprintf (GNU library) instead of sprintf If none of those is possible, be very careful about checking input size Stack protections make it harder to exploit a buffer overflow – but not impossible

C Assessment Can you easily answer all of the problems on the following slides? For each question, take a minute to write down your answer If not, please come to the C Bootcamp: Wednesday 7:30-9pm, Location TBD You need this for the rest of the course. If in doubt, come to the C Bootcamp!

C Question 1 Which of the following lines has a problem? If it does, how might you solve it? int main(int argc, char** argv) { int *a = malloc(100 * sizeof(int)); for (int i=0; i<100; i++) { if (a[i] == 0) a[i]=i; else a[i]=0; } ... free(a); return 0; 1 2 3 4 5 6

C Question 1 What can malloc return? Can malloc fail? int main(int argc, char** argv) { int *a = malloc(100 * sizeof(int)); for (int i=0; i<100; i++) { if (a[i] == 0) a[i]=i; else a[i]=0; } ... free(a); return 0; 1 2 3 4 5 6

C Question 1 Allocated memory is not initialized. What function does this? int main(int argc, char** argv) { int *a = malloc(100 * sizeof(int)); for (int i=0; i<100; i++) { if (a[i] == 0) a[i]=i; else a[i]=0; } ... free(a); return 0; 1 2 3 4 5 6

C Question 1 (bonus) Declaring a variable in a for loop requires: -std=c99 (or later standard) int main(int argc, char** argv) { int *a = malloc(100 * sizeof(int)); for (int i=0; i<100; i++) { if (a[i] == 0) a[i]=i; else a[i]=0; } ... free(a); return 0; 1 2 3 4 5 6

C Question 1 The code has been revised to address the two problems. int main(int argc, char** argv) { int *a = calloc(100 * sizeof(int)); if (a == NULL) { ...} for (int i=0; i<100; i++) { if (a[i] == 0) a[i]=i; else a[i]=0; } ... free(a); return 0;

C Question 2 What is the value of A and B? Why? #define IS_GREATER(a, b) a > b int is_greater(int a, int b) { return a > b; } int A = IS_GREATER(1, 0) + 1; int B = is_greater(1, 0) + 1;

C Question 2 A uses a macro, which does textual substitution Following the order of operations: 1 > 0 + 1 => 1 > 1 => 0 #define IS_GREATER(a, b) a > b int is_greater(int a, int b) { return a > b; } int A = IS_GREATER(1, 0) + 1; int B = is_greater(1, 0) + 1; #define IS_GREATER(a, b) a > b int A = 1 > 0 + 1;

C Question 2 B uses a function call and behaves as expected: B = 1 + 1 => 2 #define IS_GREATER(a, b) a > b int is_greater(int a, int b) { return a > b; } int A = IS_GREATER(1, 0) + 1; int B = is_greater(1, 0) + 1;

C Question 3 Which of the following lines has a problem? How would you solve the problem(s)? int *foo(int *allocate) { int a = 3; allocate = malloc(sizeof(int)); if (allocate == NULL) abort(); return &a; } 1 2 3 4

C Question 3 allocate is a local copy of the pointer “*allocate =’’ assigns to the caller’s location To allocate for the caller, foo(int **allocate) int *foo(int *allocate) { int a = 3; allocate = malloc(sizeof(int)); if (allocate == NULL) abort(); return &a; } 1 2 3 4

C Question 3 Where is a? To where does &a point? int *foo(int *allocate) { int a = 3; allocate = malloc(sizeof(int)); if (allocate == NULL) abort(); return &a; } 1 2 3 4

C Assessment COME TO THE C BOOTCAMP Did you know the answers to all of the problems? If not, COME TO THE C BOOTCAMP

C Programming Style Properly document your code Header comments, overall operation of large blocks, any tricky bits Write robust code – check error and failure conditions Write modular code Use interfaces for data structures, e.g. create/insert/remove/free functions for a linked list No magic numbers – use #define Formatting 80 characters per line Consistent braces and whitespace No memory or file descriptor leaks

C Programming Exercise Learn to use getopt Complete the code to process the commandline Write a simple calculator program

Form pairs One student needs a laptop Login to a shark machine $ wget http://www.cs.cmu.edu/~213/activities/rec6.tar $ tar xf rec6.tar $ cd rec6 $ make

man 3 getopt int getopt(int argc, char * const argv[], const char *optstring); If there are no more option characters, getopt() returns -1. optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument getopt() places a pointer to the following text in optarg getopt() finds an option character in argv that was not included in optstring, or if it detects a missing option argument, it returns '?'

If You Get Stuck on cachelab Please read the writeup. Please read the writeup. Please read the writeup. Please read the writeup! CS:APP Chapter 6 View lecture notes and course FAQ at http://www.cs.cmu.edu/~213 Office hours Sunday through Thursday 5:00-9:00pm in WeH 5207 Post a private question on Piazza man malloc, man valgrind, man gdb, gdb's help command

KEEP CALM and READ THE WRITEUP

Appendix: valgrind A suite of tools for debugging and profiling memory use, among other things find where memory that wasn't freed was allocated track origin of uninitialized values show heap usage over time detect reads and writes of invalid locations detect illegal and double frees

valgrind: Finding Memory Leaks valgrind --leak-resolution=high --leak-check=full --show- reachable=yes --track-fds=yes ./my_prog <args> your program runs as normal, though much, much slower read/write errors and uses of uninitialized values are reported as they occur un-freed memory is reported on program termination

Clang / LLVM Cachelab – Part B Matrix Transpose Clang is a gcc-equivalent C compiler Support for code analysis and transformation New methods of style checking and trace generation Compiler will check your variable usage and declarations Compiler will also instrument the code to record all memory accesses to a file