Presentation is loading. Please wait.

Presentation is loading. Please wait.

RECITATION Cache Lab and C

Similar presentations


Presentation on theme: "RECITATION Cache Lab and C"— Presentation transcript:

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

2 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

3 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!

4 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

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

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

7 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.

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

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

10 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

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

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

13 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!

14 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.

15 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!

16 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.

17 Solution 1 : Use CS:APP Wrappers
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!

18 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”); }

19 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

20 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 kesden/index/lecture_index.html for more details on how to ‘make’a Makefile

21 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

22 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

23 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!

24 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…

25 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, man pages

26 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

27 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!

28 Demo

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


Download ppt "RECITATION Cache Lab and C"

Similar presentations


Ads by Google