15-213 RECITATION CACHE LAB AND C Aishwarya Prem Renu 16 Feb 2015.

Post on 18-Jan-2016

227 views 0 download

Transcript of 15-213 RECITATION CACHE LAB AND C Aishwarya Prem Renu 16 Feb 2015.

15-213 RECITATION CACHE LAB AND C

Aishwarya Prem Renu

16 Feb 2015

Agenda

o Buffer lab – Due TOMORROW!o Cache lab – Out TOMORROW! Due 26th Febo C Assessment o Using the C Standard Libraryo Compilation (gcc and make)o Debugging Tips (Yes, you can still use GDB. )o Version Controlo Style o Demo

C Assessment

oCache Lab = First ‘Programming in C’ Lab oSteps to see if you’re ready: oCan you solve all of these upcoming C-exercises effortlessly?oThese problems test fundamental C-concepts.

oIf not, please come to the C-bootcamp

oDATE, TIME, LOCATION: TBAoYou 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

o Types: Pointers/Structso Memory Management: Malloc/Free, Valgrindo Common library functions: string.h, stdlib.h,

stdio.ho Grab-bag: macros, typedefs, function-

pointers, header-guards

Exercise #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;}

Spot the errors!

Exercise #1

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;}

Malloc does not initialize memory! So you get junk data, and the behavior of main is undefined.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 #1int main() {

int* a = malloc(100*sizeof(int));if(a == NULL) {

callerror(); //Define your own functionreturn;

}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

#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?

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 #3Safe 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 #3Safe or not?

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 #4struct 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;}

}

Spot the errors!

Exercise #4struct 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 #4struct 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. NO! Check if what malloc returned is non-NULL before you dereference!

Use the C Standard LibraryoPlease Use it! oDon’t write code that’s already been written! o Your work might have a bug or lack features o You spend time writing code that may be inefficient compared to an

existing solution.

oAll C Standard Library functions are documented. oSome of the commonly used ones are: o stdlib.h: malloc, calloc, free, exit, atoi, abs, etco string.h: strlen, strcpy, strcmp, strstr, memcpy, memset, etco stdio.h: printf, scanf, sscanf, etc

oUse the UNIX man command to look up usage / online references.

Example: getopto 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!)

o Use it to parse command line arguments and don’t write your own parser!

o Colon in “x:” indicates that it is a required argument

o optarg is set to value of option argument

o Returns -1 when no more args are present

o Useful for Cache lab!

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"); break; } }}

Write Robust CodeWe are writing code for the real world: errors will happen! oSystem calls may failoUser may enter invalid argumentsoConnections may die --- Experience with this in Proxylab! o… but your code should NOT crash!

Handle errors gracefullyo Indicate when errors happenoThey may be recoverable, you may have to terminateoRemember to free any resources in useoElse, suffer the wrath of a thousand unicornso… and our sadistic style-grading.

Solution 1 : Use CS:APP Wrapperso http://csapp.cs.cmu.edu/public/1e/ics/code/src/csapp.c

o It Has wrapper methods for all core system callso 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;

}

o Copy/paste required wrappers in source code, since we will accept only single files in earlier labs.

o Definitely include this file in your proxy lab submission!

Solution 2: Write your own checks o Example: file IO functions

o fopen: open a given file in a given mode (read/write/etc)

o fclose: close file associated with given stream

o fscanf: read data from the stream, store according to parameter format

o May be useful for Cache lab!

o Error-codes:

o fopen: return NULL

o fclose: EOF indicated

o fscanf: return fewer matched arguments, set error indicator

FILE *pfile; // file pointerif (!(pfile = fopen(“myfile.txt”, “r”))){

printf(“Could not find file. Opening default!”);

pfile = fopen(“default.txt”, “r”);}

Compilation: Using gcc o Used to compile C/C++ projects:

o List the files that will be compiled to form an executableo Specify options via flagso Use man gcc for more details

o Important Flags: o -g: produce debug information (important; used by gdb/gdbtui/valgrind)o -Werror: treat all warnings as errors (this is our default)o -Wall/-Wextra: enable all construction warningso -pedantic: indicate all mandatory diagnostics listed in C-standardo -O1/-O2: optimization levelso -o <filename>: name output binary file ‘filename’

o Example: o gcc -g -Werror -Wall -Wextra -pedantic foo.c bar.c -o baz

Compilation: make

oEasy way to automate bug shell command with lots of flags and files

oMakefiles allow you to use a single operation to compile different files together

oEfficient, because it only recompiles updated files

oLab handouts come with a Makefile: Don’t change them

omake reads Makefile and compiles your project

oSee http://www.andrew.cmu.edu/course/15-123-kesden/index/lecture_index.html for more details on how to ‘make’a Makefile

Debugging: gdbtui o Allows you to see source

o Compile with –g debug flag

o Example: gcc –g –m32 myprog.c –o myprog

o Run using gdbtui myprog

o layout src/asm/regs/split –

To display the source / assembly / registers / source & assembly layout

o focus src/asm/regs

Make the source / assembly / registers window active for scrolling

Debugging: valgrindo Use it to Find and eliminate memory errors, detect memory leaks

o Common errors you can fix: o Illegal read/write errorso Use of uninitialized valueso Illegal freeso Double frees o Overlapping source/destination addresses

o Use gcc with –g to get line number of leaks

o Use valgrind --leak-check=full for thoroughness

#ifdef DEBUG# define dbg_printf(...) printf(__VA_ARGS__)#else# define dbg_printf(...)#endif

Debugging: Small tip

Use this to easily wither print or not print without having to comment out print statements each time!

Version Control o You should use it. Now.

o Avoid suffering during large labs (malloc, proxy)

o Basic ideas: o Complete record of everything that happened in your code repositoryo Ability to create branches to test new components of codeo Ease in sharing code with others o Well, outside of 213 of course…

Version Control Basicso git init:

o Create a new repositoryo Indicated by .git file

o git status: o Show working tree-statuso Untracked files, staged files

o git add <file_name>o Stage a file to be committed (does not perform the commit)o git add . stages all files in current directory

o git commito Make a commit from all the stage fileso 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

Styleo Good documentationo Header comments, large blocks, tricky bitso Check error/failure conditions

Must program robustlyo 80 chars per line: Use grep '.\{80,\}' filename to find lines more than 80

chars o No memory or file descriptor leakso Use interfaces for data structures (Don’t repeat code)o Modularity of codeo No magic numberso Use #defineo Consistency and whitespaceo http://cs.cmu.edu/~213/codeStyle.html

Notes

oGo to the C Boot Camp if you have any doubts!

oC Boot Camp: o Time: TBDo Date: TBDo Location: TBD

oWe are style grading from Cache lab onwards!

DEMO

Acknowledgements

oDerived from recitation slides by Arjun Hans, Jack Biggs

o ftp://ftp.gnu.org/old-gnu/Manuals/gdb/html_chapter/gdb_19.html

ohttp://csapp.cs.cmu.edu/

oxkcd