The C Programming LanguageCS 241: Systems ProgrammingDiscussion, Week 1slides prepared by Sameer SundreshThe C Programming LanguageBrian KernighanDennis RitchieKen ThompsonOverviewSyntaxMemory modelDiscussion ProblemsThe C Programming LanguageC and Unix grew up togetherNative Unix systems programming languageUnix, Linux and Windows are implemented in CEssentially a portable assembly languageA canonical C program/* hello.c */#include <stdio.h>int main(int argc, char **argv){ fprintf(stdout, “Hello, CS %d \n”, 241); return 0;}A canonical C program/* hello.c */#include <stdio.h>int main(int argc, char **argv){ fprintf(stdout, “Hello, CS %d \n”, 241); return 0;}commentpreprocessor directiveformat stringmain entrypointpointer typereturn typeargument typesstandard I/O library functionThings to noticeVery similar syntax to C++ and JavaC++ was originally a front-end to C (in the '80s)But there are differences:●No objects, classes, inheritance or namespacesjust functions and datause arrays and structs to make data structures●No templates●No operator overloading (<< means shift)●No exceptions: always check return values!When you need a reference:manual pagesUnix manual pages (man pages)man [section-number] <command-or-function>man gccman 3 fprintfRelevant manual sections1 General commands (that you run from the shell)2 System calls (C functions provided by OS kernel)3 C library functionsBe aware: sometimes a command and a system call or library function have the same name.Problem 1: using fprintfLetfloat x = 1234.1234;int y = 1234;Output:Problem #1(value of x as a float)(y in decimal) (y in hexadecimal)(without the parentheses)/* hello.c */#include <stdio.h>int main(int argc, char **argv){ fprintf(stdout, “Hello, CS %d \n”, 241); return 0;}man 3 fprintfOverviewSyntaxMemory modelDiscussion ProblemsC language source code filesIt's where you write your programs.Layout of a .c fileincludes#include <stdio.h>type definitionstypedef char *string;function declarationsint main(int argc, char **argv);function definitionsint main(int argc, char **argv) { ... }C language header filesIt's how you share code between source files.Layout of a .h fileincludes#include <stdlib.h>type definitionstypedef unsigned int uint32_t;function declarationsvoid exit(int);...but no function definitionsArrays and pointersArray typestype arr[dim1][dim2]...Pointer types (more on pointers in a moment)type * type ** ...A pointer specifies the memory address of a value or the first address of an array of values.Exampleschar * A C string is just a pointer to a sequence of one or more characters in memory.int a[8], b[2][4];char *argv[], **also_argv;OverviewSyntaxMemory modelDiscussion ProblemsArrayschar a[8]; /* array of bytes */char b[4][2]; /* 2-dimensional array */int c[2]; /* array of 32-bit words */..................MemoryMemory is just a big array of bytesPointers are indicies into memoryThe type of a pointer determines whether the memory it indexes is viewed as a char, an int, etc.void indicates the no-value type.void *p = ...;(char *) p(int *) p..................Referencing and dereferencingThe & operator creates a pointer to a variable (takes the address of the memory location holding the variable), while the * operator reads the data which a pointer references:int x;int *xptr = &x;/* xptr = 0xAF981DF8 */int y = *xptr;/* y = x */Process memory layoutprogram code(“text segment”)initialized static datauninitialized data (“bss”)dynamic memorygapstacksystem data: argv, envkernel memorylow memoryNULL: 0x00x0804A0080x080496B8&argv: 0xAFA47DD4argv: 0xAFA47E44Kinds of memory allocationStatic allocationVariables declared at top level of program(outside of any function).Stack allocationVariables declared within a functionDynamic allocationmalloc(size) → pointer to allocated memoryfree(ptr) → *ptr is no longer allocatedProblem 2: What's wrongwith this program?#include <stdlib.h>int main(int argc, char **argv){ int **buf = (int **) malloc(10*sizeof(int)); for (int i = 0; i < 10; i++) { buf[i] = (int *) malloc(i*sizeof(int)); } free(buf); return 0;}Create a bugfixed version.Pointer arithmeticchar a[8]; /* array of bytes */char *p = a; /* p, a: 0xAF99EFDC */char *q = a+3; /* q: 0xAF99EFDF */..................Pointer arithmetic (2)char a[8]; /* array of bytes */char *q = a+3; /* q: 0xAF99EFDF */char *r = &a[3]; /* r: 0xAF99EFDF */..................Pointer arithmetic (3)int b[2]; /* array of 4-byte words */int *q = b+1; /* q: 0xAF99EFE0 */char *r = &b[1]; /* r: 0xAF99EFE0 */..................OverviewSyntaxMemory modelDiscussion ProblemsProblem 3: What's wrongwith this program?#include <string.h>char *twiceA(char str[10]){ char buf[20]; int n = strlen(str); strncpy(buf, str, n); strncpy(buf+n, str, n); return buf;}char *twiceB(char *str){ int n = strlen(str); return strncpy(str+n, str, n);}Hinta string is a pointer to a sequence of characters, terminated by a null: (char) 0 or '\0'Problem 4: Check memory layoutPrint out the addresses of the following:argv pointer to argument vector on stackargv[0] pointer to first argument*argv[0] first character of first argumentmain program entrypoint function - a global variable (static data) - a local variable within a function - a dynamically-allocated bufferHint: use format string “0x%08X” for a pointer.Process memory layoutprogram code(“text segment”)initialized static datauninitialized data (“bss”)dynamic memorygapstacksystem data: argv, envkernel memorylow memoryNULL: 0x00x0804A0080x080496B8&argv: 0xAFA47DD4argv: 0xAFA47E44Problem 5: Layout of argvPrint out the contents of:argvargv[0], ..., argv[argc-1]Hint: the contents of argv is an array of argc-many pointers of type char *Draw a diagram of what it looks like.Layout of argv ./ a . o u t s o m e s t u f f0xAFC85C18 0xAFC85C20 0xAFC85C25 0x00xAF8A9DE4............0xAFE550B4 (i.e., on the stack)argv
View Full Document