Agenda Attack Lab C Exercises C Conventions C Debugging

Slides:



Advertisements
Similar presentations
SEE C GO Provisional Title. Syntax Types int, float, double, char, void Identifiers foo Operators + - * / ^ Delimiters ; {} () “” ‘’ Keywords return,
Advertisements

C Tutorial Ross Shaull cs146a Why C Standard systems language – Historical reasons (OS have historically been written in C, so libraries written.
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Recitation 7 – 3/5/01 Outline Control Flow Memory Allocation –Lab 3 Details Shaheen Gandhi Office Hours: Wednesday.
C Programming - Lecture 5
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
1 Memory Allocation Professor Jennifer Rexford COS 217.
C Lab 3 C Arraylist Implementation. Goals ●Review ○ Referencing/Dereferencing ○ Free ●realloc and memmove ●ArrayList ●Debugging with GDB.
Carnegie Mellon 1 Debugging : Introduction to Computer Systems Recitation 12: Monday, Nov. 9 th, 2013 Yixun Xu Section K.
DEBUGGING IN THE REAL WORLD : Recitation 4.
CSE 451: Operating Systems Section 1. Why are you here? 9/30/102.
CS414 C Programming Tutorial Ben Atkin
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.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Carnegie Mellon 1 C Primer and Virtual Memory / : Introduction to Computer Systems 10 th Recitation, Oct. 31, 2011 Slides by: Pranav Senthilnathan.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
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
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CacheLab Recitation 7 10/8/2012. Outline Memory organization Caching – Different types of locality – Cache organization Cachelab – Tips (warnings, getopt,
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.
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.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
CSE 332: C++ debugging Why Debug a Program? When your program crashes –Finding out where it crashed –Examining program memory at that point When a bug.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
C Lab 1 Introduction to C. Basics of C Developed by Dennis Ritchie in the 1970s. Maps very easily to machine instructions. Even allows inline assembly!
CSCI Rational Purify 1 Rational Purify Overview Michel Izygon - Jim Helm.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
CSE 451: Operating Systems Section 3: Project 0 recap, Project 1.
RECITATION Cache Lab and C
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
COMP x1 Computing 2 C Outside the Style Guide, Linked Lists and Function Pointers 1.
COP 3275 – Character Strings Instructor: Diego Rivera-Gutierrez.
1 Debugging (Part 2). “Programming in the Large” Steps Design & Implement Program & programming style (done) Common data structures and algorithms Modularity.
Malloc Lab : Introduction to Computer Systems Recitation 11: Nov. 4, 2013 Marjorie Carlson Recitation A.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Carnegie Mellon 1 Malloc Lab : Introduction to Computer Systems Friday, July 10, 2015 Shen Chen Xu.
Carnegie Mellon 1 Malloc Recitation Ben Spinelli Recitation 11: November 9, 2015.
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
C Lab 2 Intermediate Pointers & Basic Structures.
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!
Hank Childs, University of Oregon April 13 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
Recitation: C Review TA’s 2 Oct 2017.
Dynamic Allocation in C
Secure Coding Rules for C++ Copyright © 2016 Curt Hill
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSE 374 Programming Concepts & Tools
Recitation 6: C Review 30 Sept 2016.
CSE 374 Programming Concepts & Tools
Checking Memory Management
C Basics.
Secure Coding Rules for C++ Copyright © Curt Hill
Recitation: C Review TA’s 19 Feb 2018.
Memory Allocation CS 217.
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.
Homework Continue with K&R Chapter 5 Skipping sections for now
CISC 361 Operating Systems Midterm Review
C Programming - Lecture 5
Dynamic Memory – A Review
C Tutorial Adapted from Wei Qian’s C tutorial slides.
Introduction to C CS 3410.
Presentation transcript:

15-213 Recitation: C Review Ben Spinelli 5 October 2015

Agenda Attack Lab C Exercises C Conventions C Debugging Version Control Compilation Demonstration

Attack Lab... is due Thursday. Start now if you haven’t yet.

Some warnings about C It’s possible to write bad code. Don’t. Watch out for implicit casting. Watch out for undefined behavior. Watch out for memory leaks. Macros and pointer arithmetic can be tricky. K&R is the official reference on how things behave.

C-0 int foo(unsigned int u) { return (u > -1) ? 1 : 0; }

C-0 int foo(unsigned int u) { return (u > -1) ? 1 : 0; } -1 is cast to an unsigned int in the comparison, so the comparison that is happening is actually u > int_max. This always returns 0.

C-1 int main() { int* a = malloc(100*sizeof(int)); for (int i=0; i<100; i++) { a[i] = i / a[i]; } free(a); return 0;

C-1 int main() { int* a = malloc(100*sizeof(int)); for (int i=0; i<100; i++) { a[i] = i / a[i]; } free(a); return 0; No value in a was initialized. The behavior of main is undefined.

C-2 int main() { char w[strlen("C programming")]; strcpy(w,"C programming"); printf("%s\n", w); return 0; }

C-2 int main() { char w[strlen("C programming")]; strcpy(w,"C programming"); printf("%s\n", w); return 0; } strlen returns the length of the string not including the null character, so we end up writing a null byte outside the bounds of w.

C-3 struct ht_node { int key; int data; }; typedef struct ht_node* node; node makeNnode(int k, int e) { node curr = malloc(sizeof(node)); curr->key = k; curr->data = e; return curr; }

C-3 struct ht_node { int key; int data; }; typedef struct ht_node* node; node makeNnode(int k, int e) { node curr = malloc(sizeof(node)); curr->key = k; curr->data = e; return curr; } node is a typedef to a struct ht_node pointer, not the actual struct. So malloc could return 4 or 8 depending on system word size.

C-4 char *strcdup(int n, char c) { char dup[n+1]; int i; for (i = 0; i < n; i++) dup[i] = c; dup[i] = ’\0’; char *A = dup; return A; }

C-4 char *strcdup(int n, char c) { char dup[n+1]; int i; for (i = 0; i < n; i++) dup[i] = c; dup[i] = ’\0’; char *A = dup; return A; } strcdup returns a stack-allocated pointer. The contents of A will be unpredictable once the function returns.

C-5 #define IS_GREATER(a, b) a > b inline int isGreater(int a, int b) { return a > b ? 1 : 0; } int m1 = IS_GREATER(1, 0) + 1; int m2 = isGreater(1, 0) + 1;

C-5 #define IS_GREATER(a, b) a > b inline int isGreater(int a, int b) { return a > b ? 1 : 0; } int m1 = IS_GREATER(1, 0) + 1; int m2 = isGreater(1, 0) + 1; IS_GREATER is a macro that is not wrapped in parentheses. m1 will actually evaluate to 0, since 1 > 0+1 = 0.

C-6 #define NEXT_BYTE(a) ((char*)(a + 1)); int a1 = 54; // &a1 = 0x100 long long a2 = 42; // &a2 = 0x200 void* b1 = NEXT_BYTE(&a1); void* b2 = NEXT_BYTE(&a2);

C-6 #define NEXT_BYTE(a) ((char*)(a + 1)); int a1 = 54; // &a1 = 0x100 long long a2 = 42; // &a2 = 0x200 void* b1 = NEXT_BYTE(&a1); void* b2 = NEXT_BYTE(&a2); b1 is a void pointer to the address 0x104. b2 is a void pointer to the address 0x208.

C Workshop If you had trouble with the previous exercises, go!!! Saturday, October 10 in the afternoon. Details TBA. Material: Undefined behavior, casting Structs, pointers Memory management Standard library functions Random stuff: macros, typedefs, function pointers, header guards… and anything else you have questions on!

The C Standard Library #include <stdlib.h> Use it. It is your friend! Don’t write code that’s already been written! Your work might have a bug or lack features All C Standard Library functions are documented. Use the UNIX man command to look up usage

Robustness Code that crashes is bad. Avoid making bad things! Don’t write code with undefined behavior Check for failed system calls and invalid input Some errors should be recoverable, others not Proxy Lab is an excellent example of this Free memory that you allocate Leaky code will crash (and code that crashes is bad!) Memory leaks will cost you style points

Robustness: Continued CSAPP wrappers check return values of system calls Terminate program when error is encountered Malloc, Free, Open, Close, Fork, etc. Super duper useful for Proxy & Shell Labs Alternatively, check for error codes yourself Useful when you don’t want program to terminate FILE *pfile; // file pointer if (!(pfile = fopen(“myfile.txt”, “r”))) { printf(“Could not find file. Opening default!”); pfile = fopen(“default.txt”, “r”); }

Quick C Tip: getopt Used for parsing command-line arguments Don’t write your own code for this. Not worth it. In fact, we actively discourage it Autograder randomizes argument order Try it: man getopt

Style Points We read and grade your code for style Style guide: http://cs.cmu.edu/~213/codeStyle.html Vim macro to highlight lines longer than 80 cols: 2mat ErrorMsg '\%80v.' Emacs users… : (setq whitespace-style '(trailing lines space-before-tab indentation space-after-tab) whitespace-line-column 80) View your annotated code on Autolab

gdb Step through C code side-by-side with Assembly Print variables, not just registers and addresses! Break at lines, not just addresses and functions! gdbtui <binary> is gdb with a less-breakable user interface. Nice for looking at your code during execution Type layout split to view Assembly alongside

gdbtui

valgrind Best tool for finding... Memory leaks Other memory errors (like double frees) Memory corruption Use gcc with -g to give you line numbers of leaks Use valgrind --leak-check=full for thoroughness

Version Control: Your Friend You may find it useful to use version control if you are already familiar with it If not, that’s okay, it’s not required. Making regular submissions to Autolab can act as a checkpointing system too.

gcc GNU Compiler Collection Is a C compiler, among other things We will give you instructions for compilation in handouts man gcc if you’re having trouble

make Lab handouts come with a Makefile Don’t modify them You write your own for Proxy Lab Examples for syntax found in previous labs make reads Makefile and compiles your project Easy way to automate tedious shell commands