Recitation: Cache Lab & C

Similar documents
Recitation: C Review. TA s 20 Feb 2017

Recitation 2/18/2012

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

ANITA S SUPER AWESOME RECITATION SLIDES

Cache Lab Implementation and Blocking

Carnegie Mellon. Cache Lab. Recitation 7: Oct 11 th, 2016

PRINCIPLES OF OPERATING SYSTEMS

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

CS61, Fall 2012 Section 2 Notes

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

Carnegie Mellon. C Boot Camp. Oct 6th, Jack Biggs Raghav Goyal Nikhil Jog

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Project #1: Tracing, System Calls, and Processes

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Recitation #11 Malloc Lab. November 7th, 2017

Recitation: Bomb Lab. September 17 th 2018

Programming Tips for CS758/858

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

18-642: Code Style for Compilers

Recitation 7 Caches and Blocking. 9 October 2017

Programming in C First meeting

Martin Brunner, Jonas Pfoh Sept. 6, Sept. 24, 2010

Lecture 07 Debugging Programs with GDB

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Exercise Session 6 Computer Architecture and Systems Programming

Programming in C week 1 meeting Tiina Niklander

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Reviewing gcc, make, gdb, and Linux Editors 1

Software Development With Emacs: The Edit-Compile-Debug Cycle

Exercise Session 2 Systems Programming and Computer Architecture

CSE 374 Programming Concepts & Tools

Carnegie Mellon. C Boot Camp. September 30, 2018

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Language Translation. Compilation vs. interpretation. Compilation diagram. Step 1: compile. Step 2: run. compiler. Compiled program. program.

HW1 due Monday by 9:30am Assignment online, submission details to come

CSE 303: Concepts and Tools for Software Development

EL2310 Scientific Programming

CS354 gdb Tutorial Written by Chris Feilbach

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Fall Programming Assignment 1 (updated 9/16/2017)

Important From Last Time

Page 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right?

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Important From Last Time

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Lectures 5-6: Introduction to C

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Lab 1: Dynamic Memory: Heap Manager

CSE 124 Discussion (10/3) C/C++ Basics

Laboratory Assignment #3. Extending scull, a char pseudo-device

CSE 333 Midterm Exam July 24, Name UW ID#

Memory Analysis tools

System Programming And C Language

Quiz 0 Review Session. October 13th, 2014

Recitation 11: More Malloc Lab

Memory Corruption 101 From Primitives to Exploit

EL2310 Scientific Programming

Arrays and Memory Management

CSE 333 Lecture 6 - data structures

TI2725-C, C programming lab, course

Lecture 03 Bits, Bytes and Data Types

de facto standard C library Contains a bunch of header files and APIs to do various tasks

CptS 360 (System Programming) Unit 4: Debugging

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

18-600: Recitation #3

CS 470 Operating Systems Spring 2013 Shell Project

CSC 1600 Memory Layout for Unix Processes"

Programming in C First meeting Tiina Niklander

12. Debugging. Overview. COMP1917: Computing 1. Developing Programs. The Programming Cycle. Programming cycle. Do-it-yourself debugging

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

CS61 Section Notes. Section 5 (Fall 2011) Topics to be covered Common Memory Errors Dynamic Memory Allocation Assignment 3: Malloc

Short Notes of CS201

18-642: Code Style for Compilers

CS61C : Machine Structures

Dynamic memory allocation

CS201 - Introduction to Programming Glossary By

Windows architecture. user. mode. Env. subsystems. Executive. Device drivers Kernel. kernel. mode HAL. Hardware. Process B. Process C.

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Summer 2016 Programming Assignment 1 Introduction The purpose of this

High Performance Programming Programming in C part 1

My malloc: mylloc and mhysa. Johan Montelius HT2016

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

ECE 2400 Computer Systems Programming, Fall 2018 PA2: List and Vector Data Structures

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

Cosc 242 Assignment. Due: 4pm Friday September 15 th 2017

just a ((somewhat) safer) dialect.

Programming Assignment 1 (PA1) - Display Bowtie

COMP 321: Introduction to Computer Systems

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

CS61C : Machine Structures

Creating a String Data Type in C

Lectures 5-6: Introduction to C

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Transcription:

15-213 Recitation: Cache Lab & C Jack Biggs 16 Feb 2015

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

Buffer Lab... Is due soon. So maybe do it soon

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

C-1 int main() { 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; }

C-1 int main() { 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; 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)); node->key = k; node->data = e; return node; }

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 BOOM! The C-4 has blown up. Your instructor has been notified. :(

C-5 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-5 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 stackallocated pointer. The contents of A will be unpredictable once the function returns.

C-6 #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-6 #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 doesn t end in a semicolon. m1 will actually evaluate to 0, since 1 > 0+1 = 0.

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

C-7 #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 0x108.

C Workshop If you had trouble with the previous exercises, go!!! Location, Time TBA (Check your email!) Material: Structs, pointers Memory management Standard library functions Random stuff: macros, typedefs, function pointers, header guards and anything else you have questions on!

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

The C Standard Library 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! 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 strongly discourage it Autograder randomizes argument order to make this task more difficult (seriously, just use getopt) Try it: man getopt

getopt: a quick example arg string int main(int argc, char *argv[]) { while ((opt = getopt(argc, argv, "nt:"))!= -1) { If the user does something wrong, we go to the? case } switch (opt) { Things without colons in the arg string case 'n': can be used for setting flags flags = 1; break; Things with colons in the arg string case 't': can specify options; the option is nsecs = atoi(optarg); placed in a variable called optarg tfnd = 1; break; case '?': if (optopt == 'c') printf ("-c requires argument\n"); } else printf (usage_string); exit(1); The case we re in is placed in a variable called optopt

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 this is why your editor sucks: (setq whitespace-style '(trailing lines spacebefore-tab indentation space-after-tab) whitespace-line-column 80) View your annotated code on Autolab

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

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 layout cmd, layout asm, layout source Change windows: focus <cmd, asm, source>

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

Using printf wisely Don t spend your time inserting and removing printfs. Disable/enable them all easily using #define Leave them in for when you want to play with it later #define DEBUG #ifdef DEBUG #define dbg_printf(...) printf( VA_ARGS ) #else #define dbg_printf(...) #endif

Inserting line numbers into debug statements Check a condition repeatedly and know which line number it failed on static inline check_list(ll_node_t *curr, int lineno) { } if (curr == NULL curr->next == NULL curr->next!= curr->next->prev) dbg_printf( Check failed on line %d\n, lineno); check_list(node_ptr, LINE )

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

Version Control: Your Friend Initialize and add files to version tracking program Commit your files as you reach checkpoints Rewind and fast-forward between commits Keep different program versions in branches malloc: branches for implicit, explicit, seglist Can sometimes be tricky to use

For dummies: Folders Keep different versions in different folders As one stage of project is finished, copy to folder Useful for trying different implementations Easy to use! Gets cluttered fast. No easy way to merge changes between folders

git git init initializes a new repository in present folder git status shows files being tracked by version control git add <file or folder> adds to version tracking git commit -am message commits with note message Look online for more examples Create branches for different implementations Merge branches, rollback to older changes

git pitfalls Be cautious when rewinding commits Follow online usage instructions carefully Stack Overflow, http://try.github.io, man git

Agenda Buffer Lab! C Exercises! C Conventions! C Debugging! Version Control! Compilation!

gcc Open source C compiler We will give you instructions for compilation in handouts man gcc, Stack Overflow 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