150 likes | 174 Views
Learn the secrets of C programming from fundamentals to advanced topics, including pointers, memory management, and parameter passing. This tutorial provides tips for efficient and bug-free coding in C language.
E N D
CS414C Programming Tutorial Ben Atkin batkin@cs.cornell.edu
Why use C? • C is not "safe" • It assumes you know what you're doing • It has a lot of scope for bugs • It's a good systems programming language • Not much is hidden • Faster than Java, more predictable performance • It has all the low-level operations
Types • No Boolean type, use int: "false" is 0, true is non-zero • Structures for grouping related data • "Like Java classes, but no methods" typedef int pid_t; /* for clarity */ struct pcb { pid_t pid; file_t openfiles[MAXOPENFILES]; ...}typedef struct pcb pcb_t; /* rename */
Constants #define KB 1024 /* constant */#define MB (KB*1024) /* note brackets */ /* wrong! ';' causes compile error */#define WARN(s) fprintf(stderr, s); /* alternative constant definition: PROC_READY==0, PROC_RUNNING==1, ... */enum { PROC_READY, PROC_RUNNING, ... };/* give it a name */typedef enum { PROC_READY, PROC_RUNNING, ... } proc_status_t;
Dynamic memory allocation • Memory must be explicitly allocated and freed #include <stdlib.h> int main() { /* declare and allocate memory */ int *ptr = (int *) malloc(sizeof(int)); *ptr = 4; /* use the memory */ free(ptr); /* free it for re-use */ }
Example memory layout 0x0 code Immutable 0x2000 Dynamic allocationmalloc(), free() heap Function calls, local variables stack 0x50000
Pointer initialisation • Always initialise, even if only to NULL #include <stdlib.h> int main() { int x = 5; int *ptr; x = *ptr; /* unpredictable: initialise! */ ptr = &x; /* good initialisation */ *ptr = 4; /* bad initialisation */ *ptr = NULL; /* good 5 */ }
Changing pointer types • Pointers can be converted between types • type_t *x = (type_t *) y; • (void *) equivalent to any type, e.g. implementation of generic collections • malloc() returns a void * • Useful for low-level operations • e.g. networking, memory allocation
Parameter passing • Functions can take pointer argumentsint function(int *in, int *out); • Two main purposes • So that function can modify the variable (pass-by-reference) • Efficiency: passing "big_struct_t x" is not efficient, passing &x is efficient • Return values are often used to signal errors • e.g. return value 0=="no error", non-zero==error
Parameter passing void function(int *arg1, char **arg2) { ...}int main(void) { int x = 5; int *y = &x; char string[] = "Hello, world!"; char *ptr = NULL; function(&x, NULL); function(y, &ptr); /* *ptr can be changed */ function(y, &string); /* probably wrong */}
Pointers and functions /* function returning integer */int func();/* function returning pointer to integer */int *func();/* pointer to function returning integer */int (*func)();/* pointer to function returning pointer to integer */int *(*func)(); Hide this complexity with typedefs! e.g. typedef void (*interrupt_handler)(void *); void an_interrupt_handler(void *arg);
#include <stdio.h>#include "queue.h"int main() { queue_t queue; queue_init(&queue); ...} #include "queue.h"void queue_init(queue_t* q) {...}... Multiple modules typedef struct { ...} queue_t;void queue_init(queue_t* q); Standard library
#include <stdio.h>#include "defs.h"int main() { ... if (tickcount > 5) set_timer();} #include "defs.h"int tickcount = 0;void set_timer() { printf("Timer at %d.", tickcount);} External definitions /* defs.h */...extern int tickcount;...
Hints and tips • Avoid bugs in your program: • don't index past the end of an array • don't return pointers to local variables from functions • initialise data properly, especially pointers • check error codes (no exceptions in C) • free() what you malloc() • destroy all pointers to what you free() • ... or else you might only find them when you least expect it!
Hints and tips • Program safely! • Plan before you start • Pay attention to compiler warnings • Use assert()to check conditions are valid • Indent your code to make it easy to read • Beware of complicated #defines • Use the debugger • If you're serious about C, get K&R • Lots of library functions for you to use