47
ì Computer Systems and Networks ECPE 170 – Jeff Shafer – University of the Pacific C Programming

C Programming - University of the Pacificecs-network.serv.pacific.edu/ecpe-170/slides/05cprogramming.pdf · ì Computer Systems and Networks ECPE 170 –Jeff Shafer –University

  • Upload
    vunhan

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

ìComputer Systems and NetworksECPE170– JeffShafer– UniversityofthePacific

CProgramming

Lab Schedule

Activitiesì ThisWeek

ì IntrotoCì IntrotoBuildToolsand

Makefilesì Lab3– BuildTools

ì NextWeekì Lab4– CProgramming

Project

Deadlinesì Lab3– Feb6th 2017

by5am

ì Lab4– Feb20th 2017by5am

Spring2017ComputerSystemsandNetworks

2

Person of the Day: Dennis Ritchie

ì Creatorof Cprogramminglanguage

ì Co-creatorofUnix(withKenThompson,BrianKernighan,andothersatBellLabs)

ì WinnerofACMTuringAward

ì 9/9/1941—10/12/2011

Spring2017ComputerSystemsandNetworks

3

Person of the Day: Dennis Ritchie

ì “Prettymucheverythingonthewebusesthosetwothings:CandUNIX.ThebrowsersarewritteninC.TheUNIXkernel— thatprettymuchtheentireInternetrunson— iswritteninC.WebserversarewritteninC,andifthey’renot,they’rewritteninJavaorC++,whichareCderivatives,orPythonorRuby,whichareimplementedinC.AndallofthenetworkhardwarerunningtheseprogramsIcanalmostguaranteewerewritteninC.It’sreallyhardtooverstatehowmuchofthemoderninformationeconomyisbuiltontheworkDennisdid.”ì RobPike,BellLabs/Google

Spring2017ComputerSystemsandNetworks

4

Spring2017ComputerSystemsandNetworks

5

DennisRitchieandKenThompsonuseateletypewritertorunaprogramonaUNIX-basedcomputersystemtheyco-foundedatBellLabsinNewJersey.Theirdevelopmentworkmorethan40yearsagofacilitatedtherealizationoftheInternet.

ìC Programming

Spring2017ComputerSystemsandNetworks

6

C++ Features Not in C

ì Noclasses /object-orientedprogramming

ì Nonew /delete

ì Nostreamoperators(<<and>>),cin,cout,…

ì NoC++StandardLibraries(e.g.iostream)

ì bool keywordì AddedinC99standard

ì Declarevariablesanywhereinsidefunctionì AddedinC99standard

Spring2017ComputerSystemsandNetworks

7

Output with printf()

ì printf("This is a string\n");

ì printf("The integer is %i\n", num);

ì printf("The floating-point values are %g and %g\n", num1, num2);

Spring2017ComputerSystemsandNetworks

8

Output with printf()

Spring2017ComputerSystemsandNetworks

9

Format “Type”Code CorrespondingVariableType

d ori int (interpret assigned2’s comp)

u int (interpretasunsigned)

x int (printashexadecimal)

f org float/double

c char

s string(null-terminated arrayofchars)

Prefixwithl orll (i.e.“long”or“longlong”forlarger64-bitdatatypes)

ì Lotsofformattingoptionsnotlistedhere…ì #ofdigitsbefore/afterdecimalpoint?ì Padwithzeros?

Input with scanf()

ì Inputfromconsole

ì scanf("%d %c", &myint, &mychar)

ì Requirestheaddress ofthedestinationvariableì Usethe& operatortoobtainaddress

ì Caveat:Arraynamesarealreadythe“addressof”!ì char myarray[8];

scanf("%s", myarray)

Spring2017ComputerSystemsandNetworks

10

No& neededhere!

Documentation

ì Man(ual)pagesexistforcommonprogrammingfunctionstoo

ì unix> man printf

ì unix> man scanf

Spring2017ComputerSystemsandNetworks

11

Structures

Spring2017ComputerSystemsandNetworks

12

struct database{

int id_number;int age;float salary;

};

int main(){

struct database employee; employee.age = 22;employee.id_number = 1;employee.salary = 12000.21;

}

ìC-Strings (Arrays of Characters)

13

Spring2017ComputerSystemsandNetworks

C Strings

ì Thereisnosuchthingasa“string”inC!

ì Whatdoyouget?Anarrayofcharactersì Terminatedbythenullcharacter'\0'

ì Mustmanipulateelementbyelement…ì Notenoughroominthearray?Needabiggerarray

Spring2017ComputerSystemsandNetworks

14

Arrays of Characters

ì char phrase[]="Math";

15

phrase

M A T H \0

phrase[0] phrase[1] phrase[2] phrase[3] phrase[4]

Nullterminatorcharacter(Endofstring)

Spring2017ComputerSystemsandNetworks

Arrays of Characters

ì char phrase[8]="Math";

16

phrase

M A T H \0 ??? ??? ???

phrase[0] phrase[1] phrase[2] phrase[3] phrase[4] phrase[5] phrase[6] phrase[7]

printf("%s\n", phrase); Printsuntilitreachesthe\0 character!

Spring2017ComputerSystemsandNetworks

Helpful Library for Character Arrays

ì #include <string.h>

ì Usefulfunctionsì strcpy - Stringcopyì strcmp - Stringcompareì strlen - Stringlengthì strcat - Stringconcatenate

17

Spring2017ComputerSystemsandNetworks

String Copy

ì char phrase1[] = "Math";

ì char phrase2[8];

ì strcpy(phrase2, phrase1);

18

phrase1

M A T H \0

phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4]

phrase2

M A T H \0 ??? ??? ???

phrase2[0] phrase2[1] phrase2[2] phrase2[3] phrase2[4] phrase2[5] phrase2[6] phrase2[7]

Spring2017ComputerSystemsandNetworks

String Concatenation

ì char phrase1[8] = “Comp”;

ì char phrase2[] = “Sci”;

ì strcat(phrase1, phrase2);

19

phrase1

C O M P S

phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4]

phrase2

S C I \0

phrase2[0] phrase2[1] phrase2[2] phrase2[3]

C I \0

phrase1[5] phrase1[6] phrase1[7]

Youcannotdothis:phrase2=phrase1+phrase2;

Spring2017ComputerSystemsandNetworks

ctype Library

ì Usefulforcharactermanipulation

ì #include <ctype.h>

ì toupper(char) /tolower(char) – Convertscharactertouppercaseorlowercaseì Example:

char c = toupper('a');printf("%c", c); // A

20

Spring2017ComputerSystemsandNetworks

ctype Library

ì isalpha(char) – Isthecharacteraletter?

ì isdigit(char) – Isthecharacteranumber0-9?

ì isspace(char) – Isthecharacterwhitespace?(spaceornewlinecharacter)

ì ispunct(char) – Isthecharacterpunctuation?(technically,avisiblecharacterthatisnotwhitespace,aletter,oranumber)

ì …andseveralothervariations

21

Spring2017ComputerSystemsandNetworks

ìMemory Management

Spring2017ComputerSystemsandNetworks

22

Memory Allocation with malloc()

ì #include <stdlib.h>

ì void * malloc(int size)

ì Allocate regioninmemory(aka“new”)ì Argument:Sizeofregioninbytestoallocateì Returnvalue:Pointertotheregion

ì void free(void * ptr)ì De-allocateregioninmemory(aka“delete”)ì Argument:Pointertotheregion

Spring2017ComputerSystemsandNetworks

23

Memory Allocation with malloc()

ì void * calloc(int count, int size)

ì Basicallythesameasmalloc!ì Imagineyouwantanarrayofelements…

ì Argument1:#ofelementstoallocateì Argument2:Sizeofeachelementinbytesì Returnvalue:Pointertotheregion

Spring2017ComputerSystemsandNetworks

24

Memory Allocation with malloc()

ì void * realloc(void *ptr, int size);

ì Resize adynamicregionofmemoryì Notethatitmightmove toanewaddress!

ì Argument:Pointertotheoriginalregionì Argument2:Desiredsizeinbytesofnewregionì Returnvalue:Pointertothenewregion

ì Itmightbeatthesameaddressifyoumadeitsmallerì Itmightbeatanewaddressifyoumadeitlarger

Spring2017ComputerSystemsandNetworks

25

Memory Management

ì Whoimplementedmalloc()?

ì CStandardLibrary:#include <stdlib.h>

ì TherearedifferentCStandardLibraryimplementations!ì Android:Bionicì Apple:BSD-based/Proprietaryì Microsoft:ProprietaryCRuntimeLibraryì Linux:GNUCLibrary(glibc)

http://www.gnu.org/software/libc/

Spring2017ComputerSystemsandNetworks

26

Memory Management

ì Wheredoesthemalloc()memorycomefrom?

ì TheHeap:ì Aregionofmemoryfordynamicmemoryallocationì Per-process– eachprogramgetsitsownheapì Managedbymalloc()andrelatedfunctionsì Differentfromthestack,whichisforstaticvariables

(knownatcompile-time)

Spring2017ComputerSystemsandNetworks

27

Memory Management

ì malloc() outline:

1. Callmalloc() andrequestmemory

2. malloc() checksexistingheapsizeì Sufficient?Updatebookkeepingtomarkspaceas

“used”andreturnaddresstoyourprogramì Insufficient?

1. Calloperatingsystem viabrk()/nmap() togrowtheheap(plusalittleextraforfuturerequests)

2. Updatebookkeepingandreturnaddresstoyourprogram

Spring2017ComputerSystemsandNetworks

28

Memory Management

ì Whydoweneedtocallfree() aftercallingmalloc()?ì Memoryleakì malloc() cannotre-usethatspaceever,because

itsinternalbookkeepingstillthinksthatregionisused

ì Willonlyberecovereduponterminatingprogramì Operatingsystemwipesoutallthememoryallocated

toyourprocess(stack,heap,etc…)

Spring2017ComputerSystemsandNetworks

29

Memory Management

ì OScreatesvirtualmemory spaceforprocesswhenstarted

ì Regionishuge(full32or64bitspace)ì Not fullymappedto

physicalmemoryì Otherwiseyou

couldonlyfit1programinmemory

Spring2017ComputerSystemsandNetworks

30

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

VirtualMemorySpacefornewprocess

Memory Management

ì OSloadsintheprogramfromdisk

ì “Text”regionì Programcode

ì “Data”regionì Programfixed

data

Spring2017ComputerSystemsandNetworks

31

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Memory Management

ì Stack createdtotrackprogramfunctioncallsandlocalvariables

Spring2017ComputerSystemsandNetworks

32

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Memory Management

ì Heap createdtostoredynamicmemoryfrommalloc()andrelatedfunctions

ì Nottoscale–thisunusedregionishuge!

Spring2017ComputerSystemsandNetworks

33

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Memory Management

ì Programstartsrunning

ì malloc()allocatessomememory

Spring2017ComputerSystemsandNetworks

34

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Memory Management

ì Originalheapspaceeventuallyfillsup

ì malloc()requestsadditionalspacefromthekernelbyusingbrk()systemcall

Spring2017ComputerSystemsandNetworks

35

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Newspace

Memory Management

ì free()deallocatesblocksfromtheheap

Spring2017ComputerSystemsandNetworks

36

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Memory Management

ì Programterminates

ì OSexpungesentirevirtualaddressspaceì Everythingis

deleted

Spring2017ComputerSystemsandNetworks

37

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Buffer Overflow Vulnerability

ì Whatisabufferoverflowbug?ì char buf1[8]=“”;

char buf2[8]=“”;strcat(buf1, “excessive”);

ì Endupoverwritingtwocharactersbeyondbuf1!

38

Spring2017ComputerSystemsandNetworks

Buffer Overflow Vulnerability

ì Whyisabufferoverflowbugdangerous?

ì Whatisbeyondmybufferinmemory?ì Othervariablesanddata?(probablybuf2)ì Thestack?(furtherout)ì Thereturnaddresstojumptoaftermyfunction

finishes?

ì Ifappisrunningasadministrator,attackernowhasfullaccess!

39

Spring2017ComputerSystemsandNetworks

Memory Management

ì LimitlessopportunitiesinCforerrorsregardingmemoryLì Forgettingtofree() somedynamicmemoryì Tryingtofree() dynamicmemorymorethanonceì Losingapointertodynamicmemory(memoryis“lost”)ì Accessingarrayelementspasttheendofthearrayì Mis-calculatingarraypointersthatmisstheirdesired

target

ì Willlearnatool(Valgrind)inLab5toanalyzeyourprogramanddetect/traceerrors

40

Spring2017ComputerSystemsandNetworks

What’s the Error?

Spring2017ComputerSystemsandNetworks

41

char *a = malloc(128*sizeof(char));char *b = malloc(128*sizeof(char));b = a;free(a);free(b);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

What’s the (Potential) Error?

Spring2017ComputerSystemsandNetworks

42

char *a = malloc(128*sizeof(char));

dataLen = <some value...>

// Copy “dataLen” bytes// starting at *data to *amemcpy(a, data, dataLen);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

What’s the Error?

Spring2017ComputerSystemsandNetworks

43

ptr = (char *) malloc(strlen(string_A)); strcpy(ptr, string_A);

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

What’s the Error?

Spring2017ComputerSystemsandNetworks

44

int *get_ii(){

int ii = 2; // Local stack variablereturn &ii;

}main(){int *ii;ii = get_ii(); ... Do stuff using ii pointer

}

http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

Spring2017ComputerSystemsandNetworks

45

http://xkcd.com/371/

Memory Management

ì What’saNULLpointer?ì Pointervalueis0x000000000ì Meaning isthatthepointerisnotpointinganywhere

ì WhathappensifyoudereferenceaNULLpointer?ì Tellingthecomputertoreadfrom(orwrite)tothe

valuestoredinthepointer,whichis0x000000000ì Behaviorundefinedandgenerallyunpleasanton

variouscomputersystems

Spring2017ComputerSystemsandNetworks

46

Memory Management

ì “Segfault”=SegmentationFault

ì Yourprogramtriedtoreadorwriteavirtualmemoryaddress thatisnotallowedì Triedtoreadmemoryoutsideofprogrambounds?ì Triedtowriteread-onlymemoryregions?(usedfor

programdata)

ì “Segmentation”wasthenameofanoldsystem(backbeforeIntel386processors)usedtodividephysicalcomputermemoryintomanyvirtualaddressregions,oneperapplicationprocessì TheSegfault namestuckeventhoughwenowusepaging

tomanagevirtualmemory

Spring2017ComputerSystemsandNetworks

47