Aishwarya Prem Renu 16 Feb 2015 Agenda Buffer lab Due TOMORROW Cache lab Out TOMORROW Due 26 th Feb C Assessment Using the C Standard Library Compilation gcc and make ID: 781414
Download The PPT/PDF document "15-213 RECITATION Cache Lab and C" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
15-213 RECITATION Cache Lab and C
Aishwarya
Prem
Renu
16 Feb 2015
Slide2Agenda Buffer lab – Due TOMORROW!
Cache lab – Out TOMORROW! Due 26
th
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!
Slide4Important C Topics
Types: Pointers/
Structs
Memory
Management:
Malloc
/Free,
ValgrindCommon library functions: string.h, stdlib.h, stdio.hGrab-bag: macros, typedefs, function-pointers, header-guards
Slide5Exercise #1int 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!
Slide6Exercise #1int 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?
Slide7Exercise #1int main()
{
int* a = malloc(100*sizeof(int
));
i
f(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.
Slide8Exercise #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?
Slide9int * funfun(
int
* allocate)
{
allocate =
malloc
(sizeof(int)); int a = 3; return &a;}i
nt main
{
int * ptr1;
int * ptr2 = funfun(ptr1); printf(“%p %p”, ptr1, ptr2); return 1; }Exercise #3Safe or not?
Slide10int * funfun(
int
* allocate)
{
allocate =
malloc
(sizeof(int)); int a = 3; return &a;}i
nt 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
Slide11Exercise #4
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; }
}
Spot the errors!
Slide12Exercise #4
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?
Slide13Exercise #4
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.
NO! Check if what
malloc
returned is non-NULL before you dereference!
Slide14Use the C Standard LibraryPlease Use it!
Don’t
write code that’s already been written
!
Y
our
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, etcstring.h:
strlen
,
strcpy
,
strcmp
, strstr, memcpy, memset, etcstdio.h: printf, scanf, sscanf, etcUse the UNIX man command to look up usage / online references.
Slide15Example: getopt
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 argumentoptarg is set to value of option argumentReturns -1 when no more args are presentUseful 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;
}
}
}
Slide16Write Robust CodeWe are writing code for the real world: errors will
happen!
S
ystem
calls may fail
U
ser
may enter invalid argumentsConnections may die --- Experience with this in Proxylab! … but your code should NOT crash!Handle errors gracefullyIndicate when errors happenThey 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.
Slide17Solution 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!
Slide18Solution 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 streamfscanf: read data from the stream, store according to parameter format
May
be useful for Cache lab!
Error-codes:
fopen
:
return NULLfclose: EOF indicatedfscanf: 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”);}
Slide19Compilation: 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 detailsImportant 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
Slide20Compilation: make
Easy way to automate bug shell command with lots of flags and files
Makefile
s
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 themmake reads Makefile and compiles your projectSee http://www.andrew.cmu.edu/course/15-123-kesden/index/lecture_index.html for more details on how to ‘
make
’
a
M
akefile
Slide21Debugging: gdbtui
Allows you to see source
Compile with
–g
debug flag
Example:
gcc
–g –m32 myprog.c –o myprogRun using gdbtui myproglayout
src
/
asm
/
regs
/split – To display the source / assembly / registers / source & assembly layoutfocus src/asm/regsMake the source / assembly / registers window active for scrolling
Slide22Debugging: valgrind
Use it to Find and eliminate memory
errors, detect memory leaks
Common
errors you can fix:
Illegal
read/write
errorsUse of uninitialized valuesIllegal freesDouble frees
Overlapping
source/destination
addresses
Use
gcc
with –g to get line number of leaks Use valgrind --leak-check=full for thoroughness
Slide23#ifdef DEBUG# define
dbg_printf
(...)
printf
(__VA_ARGS__)
#else
# define
dbg_printf(...)#endifDebugging: Small tipUse this to easily wither print or not print without having to comment out print statements each time!
Slide24Version Control You should use it. Now.
Avoid
suffering during large labs (
malloc
,
proxy)
Basic
ideas: Complete record of everything that happened in your code repositoryAbility to create branches to test new components of codeEase in sharing code with others Well, outside of 213 of course…
Slide25Version Control Basicsgit
init
:
Create a new repository
Indicated by
.
git filegit status: Show working tree-statusUntracked 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 directorygit commitMake a commit from all the stage filesgit commit -m “Commit message”
Warning Be cautious when rewinding commits!!!
Follow online usage instructions carefully!Use Stack Overflow, http://try.github.io,
man pages
Slide26StyleGood documentationHeader 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 leaksUse interfaces for data structures (Don’t repeat code)Modularity of codeNo magic numbersUse #defineConsistency and whitespace
http
://cs.cmu.edu/~213/codeStyle.html
Slide27Notes 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!
Slide28Demo
Slide29AcknowledgementsDerived 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