RECITATION Cache Lab and C

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

Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
SPLINT STATIC CHECKING TOOL Sripriya Subramanian 10/29/2002.
C Programming - Lecture 5
DEBUGGING IN THE REAL WORLD : Recitation 4.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Guide To UNIX Using Linux Third Edition
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Carnegie Mellon 1 Debugging and Version control / : Introduction to Computer Systems 12 th Recitation, Nov. 14, 2011 Slides by: Lin Xiao(lxiao)
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.
Cache Lab Implementation and Blocking
Cache Lab Implementation and Blocking
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
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.
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
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.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Carnegie Mellon C Boot Camp 10 Oct 2015 Ben Spinelli.
1 CSC2100B Data Structure Tutorial 1 Online Judge and C.
C LANGUAGE Characteristics of C · Small size
Project 2: User Programs Abdelmounaam Rezgui Acknowledgment: The content of some slides is partly taken from Josh Wiseman’s presentation.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
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.
Files A collection of related data treated as a unit. Two types Text
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
CSE 333 – SECTION 2 Memory Management. Questions, Comments, Concerns Do you have any? Exercises going ok? Lectures make sense? Homework 1 – START EARLY!
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Hank Childs, University of Oregon April 13 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
Recitation: C Review TA’s 2 Oct 2017.
Dynamic Allocation in C
Content Coverity Static Analysis Use cases of Coverity Examples
LINKED LISTS.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Cs288 Intensive Programming in Linux
C Primer.
A bit of C programming Lecture 3 Uli Raich.
Recitation 6: C Review 30 Sept 2016.
CS 537 Section 1 Programming in Unix and C
Checking Memory Management
C Short Overview Lembit Jürimägi.
C programming language
Recitation: C Review TA’s 19 Feb 2018.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Chapter 14 - Advanced C Topics
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.
Virtual Memory CSCI 380: Operating Systems Lecture #7 -- Review and Lab Suggestions William Killian.
File Input and Output.
Programming in C Miscellaneous Topics.
Programming in C Miscellaneous Topics.
Introduction to Static Analyzer
CSCI 380: Operating Systems William Killian
Homework Continue with K&R Chapter 5 Skipping sections for now
C Programming - Lecture 5
Dynamic Memory – A Review
Makefiles, GDB, Valgrind
15213 C Primer 17 September 2002.
SPL – PS1 Introduction to C++.
Presentation transcript:

15-213 RECITATION Cache Lab and C Aishwarya Prem Renu 16 Feb 2015

Agenda Buffer lab – Due TOMORROW! Cache lab – Out TOMORROW! Due 26th Feb C Assessment Using the C Standard Library Compilation (gcc and make) Debugging Tips (Yes, you can still use GDB. ) Version Control Style Demo

C Assessment Cache Lab = First ‘Programming in C’ Lab Steps to see if you’re ready: Can you solve all of these upcoming C-exercises effortlessly? These problems test fundamental C-concepts. If not, please come to the C-bootcamp DATE, TIME, LOCATION: TBA You need this for the rest of the course. So, if in doubt, COME TO THE BOOTCAMP, and get all your doubts cleared!

Important C Topics Types: Pointers/Structs Memory Management: Malloc/Free, Valgrind Common library functions: string.h, stdlib.h, stdio.h Grab-bag: macros, typedefs, function-pointers, header-guards

Exercise #1 Spot the errors! 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;

Exercise #1 Malloc does not initialize memory! So you get junk data, and the behavior of main is undefined. int main() { int* a = malloc(100*sizeof(int)); /* Q.3 Is anything missing here? */ for (int i=0; i<100; i++) if (a[i] == 0) a[i]=i; else a[i]=0; } int b = sizeof(a); int c = (a == &a[0]); free(a); return 0; Q.1 What can you use instead of malloc, so you can be sure of the contents? Q.2 What are the values of b and c? Q.4 What does free(a) do?

Exercise #1 Malloc may return NULL! int main() { int* a = malloc(100*sizeof(int)); if(a == NULL) { callerror(); //Define your own function return; } for (int i=0; i<100; i++) if (a[i] == 0) a[i]=i; else a[i]=0; free(a); int b = sizeof(a); // b = 8 (for 64-bit systems) int c = (a == &a[0]); // c = 1 return 0; Malloc may return NULL! In that case, you would get a dreaded Segmentation fault when you try to dereference. And Nope, you do not want that happening.

Exercise #2 Q.1 What are the values of c and d? #define SUM(a,b) a+b int sum(int a, int b) { return a+b; } int main { int c = SUM(2,3)*4; int d = sum(2,3)*4; return 1; Q.1 What are the values of c and d?

Exercise #3 Safe or not? int * funfun(int * allocate) { allocate = malloc(sizeof(int)); int a = 3; return &a; } int main int * ptr1; int * ptr2 = funfun(ptr1); printf(“%p %p”, ptr1, ptr2); return 1;

Exercise #3 Safe or not? int * funfun(int * allocate) { allocate = malloc(sizeof(int)); int a = 3; return &a; } int main int * ptr1; int * ptr2 = funfun(ptr1); printf(“%p %p”, ptr1, ptr2); return 1; Function returning address of local variable! Not allowed that was allocated on the stack and is not safe to access after you return from funfun! Note: Printing pointer values

Exercise #4 Spot the errors! struct node { int a; struct node* next; }; typedef struct node * nodeptr; int main() nodeptr ** data = (nodeptr **)malloc(4*sizeof(nodeptr *)); for( int i = 0; i<4; i++) data[i] = (nodeptr *)malloc(3*sizeof(nodeptr)); } for( int j = 0; j<3; j++) data[0][j]->a = 213; } }

Exercise #4 Segmentation Fault. Q. Now, are all accesses safe? struct node { int a; struct node* next; }; typedef struct node * nodeptr; int main() nodeptr ** data = (nodeptr **)malloc(4*sizeof(nodeptr *)); for( int i = 0; i<4; i++) data[i] = (nodeptr *)malloc(3*sizeof(nodeptr)); } for( int j = 0; j<3; j++) data[0][j] = malloc(sizeof(struct node)); data[0][j]->a = 213; } /* Free everything you malloc! */ } data[i] has been allocated to be of type nodeptr *, However, each of these nodeptr in the heap do not point to anything yet, and are uninitialized! Hence, when you dereference data[0][j], you get a Segmentation Fault. Q. Now, are all accesses safe?

Exercise #4 Segmentation Fault. data[i] has been allocated to be of type nodeptr *, However, each of these nodeptr in the heap do not point to anything yet, and are uninitialized! Hence, when you dereference data[0][j], you get a Segmentation Fault. struct node { int a; struct node* next; }; typedef struct node * nodeptr; int main() nodeptr ** data = (nodeptr **)malloc(4*sizeof(nodeptr *)); for( int i = 0; i<4; i++) data[i] = (nodeptr *)malloc(3*sizeof(nodeptr)); } for( int j = 0; j<3; j++) data[0][j] = malloc(sizeof(struct node)); data[0][j]->a = 213; } /* Free everything you malloc! */ } NO! Check if what malloc returned is non-NULL before you dereference!

Use the C Standard Library Please Use it! Don’t write code that’s already been written! Your work might have a bug or lack features You spend time writing code that may be inefficient compared to an existing solution. All C Standard Library functions are documented. Some of the commonly used ones are: stdlib.h: malloc, calloc, free, exit, atoi, abs, etc string.h: strlen, strcpy, strcmp, strstr, memcpy, memset, etc stdio.h: printf, scanf, sscanf, etc Use the UNIX man command to look up usage / online references.

Example: getopt int main(int argc, char** argv) { int opt, x; /* looping over arguments */ while(-1 != (opt = getopt(argc, argv, “x:"))) switch(opt) case 'x': x = atoi(optarg); break; default: printf(“wrong argument\n"); } getopt is used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. (From the man pages! See, it’s really helpful!) Use it to parse command line arguments and don’t write your own parser! Colon in “x:” indicates that it is a required argument optarg is set to value of option argument Returns -1 when no more args are present Useful for Cache lab!

Write Robust Code We are writing code for the real world: errors will happen! System calls may fail User may enter invalid arguments Connections may die --- Experience with this in Proxylab! … but your code should NOT crash! Handle errors gracefully Indicate when errors happen They may be recoverable, you may have to terminate Remember to free any resources in use Else, suffer the wrath of a thousand unicorns … and our sadistic style-grading.

Solution 1 : Use CS:APP Wrappers http://csapp.cs.cmu.edu/public/1e/ics/code/src/csapp.c It Has wrapper methods for all core system calls Explicitly checks for return values and then calls unix_error if something went wrong void *Malloc(size_t size) { void *p; if ((p = malloc(size)) == NULL) unix_error("Malloc error"); return p; } Copy/paste required wrappers in source code, since we will accept only single files in earlier labs. Definitely include this file in your proxy lab submission!

Solution 2: Write your own checks Example: file IO functions fopen: open a given file in a given mode (read/write/etc) fclose: close file associated with given stream fscanf: read data from the stream, store according to parameter format May be useful for Cache lab! Error-codes: fopen: return NULL fclose: EOF indicated fscanf: return fewer matched arguments, set error indicator FILE *pfile; // file pointer if (!(pfile = fopen(“myfile.txt”, “r”))) { printf(“Could not find file. Opening default!”); pfile = fopen(“default.txt”, “r”); }

Compilation: Using gcc Used to compile C/C++ projects: List the files that will be compiled to form an executable Specify options via flags Use man gcc for more details Important Flags: -g: produce debug information (important; used by gdb/gdbtui/valgrind) -Werror: treat all warnings as errors (this is our default) -Wall/-Wextra: enable all construction warnings -pedantic: indicate all mandatory diagnostics listed in C-standard -O1/-O2: optimization levels -o <filename>: name output binary file ‘filename’ Example: gcc -g -Werror -Wall -Wextra -pedantic foo.c bar.c -o baz

Compilation: make Easy way to automate bug shell command with lots of flags and files Makefiles allow you to use a single operation to compile different files together Efficient, because it only recompiles updated files Lab handouts come with a Makefile: Don’t change them make reads Makefile and compiles your project See http://www.andrew.cmu.edu/course/15-123- kesden/index/lecture_index.html for more details on how to ‘make’a Makefile

Debugging: gdbtui Allows you to see source Compile with –g debug flag Example: gcc –g –m32 myprog.c –o myprog Run using gdbtui myprog layout src/asm/regs/split – To display the source / assembly / registers / source & assembly layout focus src/asm/regs Make the source / assembly / registers window active for scrolling

Debugging: valgrind Use it to Find and eliminate memory errors, detect memory leaks Common errors you can fix: Illegal read/write errors Use of uninitialized values Illegal frees Double frees Overlapping source/destination addresses Use gcc with –g to get line number of leaks Use valgrind --leak-check=full for thoroughness

Debugging: Small tip #ifdef DEBUG # define dbg_printf(...) printf(__VA_ARGS__) #else # define dbg_printf(...) #endif Use this to easily wither print or not print without having to comment out print statements each time!

Version Control You should use it. Now. Avoid suffering during large labs (malloc, proxy) Basic ideas: Complete record of everything that happened in your code repository Ability to create branches to test new components of code Ease in sharing code with others Well, outside of 213 of course…

Version Control Basics git init: Create a new repository Indicated by .git file git status: Show working tree-status Untracked files, staged files git add <file_name> Stage a file to be committed (does not perform the commit) git add . stages all files in current directory git commit Make a commit from all the stage files git commit -m “Commit message” Warning Be cautious when rewinding commits!!! Follow online usage instructions carefully! Use Stack Overflow, http://try.github.io, man pages

Style http://cs.cmu.edu/~213/codeStyle.html Good documentation Header comments, large blocks, tricky bits Check error/failure conditions Must program robustly 80 chars per line: Use grep '.\{80,\}' filename to find lines more than 80 chars No memory or file descriptor leaks Use interfaces for data structures (Don’t repeat code) Modularity of code No magic numbers Use #define Consistency and whitespace http://cs.cmu.edu/~213/codeStyle.html

Notes Go to the C Boot Camp if you have any doubts! C Boot Camp: Time: TBD Date: TBD Location: TBD We are style grading from Cache lab onwards!

Demo

Acknowledgements Derived from recitation slides by Arjun Hans, Jack Biggs ftp://ftp.gnu.org/old-gnu/Manuals/gdb/html_chapter/gdb_19.html http://csapp.cs.cmu.edu/ xkcd