c programming 2 - university of the pacific · pointer arithmetic ì only addition and subtraction...

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

Upload: others

Post on 05-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ìComputerSystemsandNetworksECPE170–JeffShafer–UniversityofthePacific

CProgramming2

Page 2: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

LabSchedule

Activitiesì  ThisWeek

ì  IntrotoC2ì  Lab4–CProgramming

Project

Deadlinesì  Lab3–Feb4th2020

by5am

ì  Lab4–Feb18th2020by5am

Spring2020ComputerSystemsandNetworks

2

Page 3: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

PointerArithmetic

ì  Onlyadditionandsubtractionareallowedwithpointers

ì  Allpointersincreaseanddecreasebythelengthofthedata-typetheypointto

ì  Exampleì  Ifanintegerpointer,iptrholdsaddress32,then

aftertheexpressioniptr++,iptr willhold36(assumingintegeris4bytes).

ComputerSystemsandNetworks

3

Spring2020

Page 4: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Problem1Thenameofthearrayisactuallyapointerpointingtothefirstelementofthearray.

printf(“\n”, %u:”, array+3); //prints?______printf(“\n”, %u:”, *(array+3)); //prints?______

Subscript [0] [1] [2] [3] [4] Value 5 6 4 8 2

Address 65528 65532 65536 65540 65544

Consider an integer array named array.

printf(“\n %u:”, array); //prints 65528

printf(“\n %u:”, array+2); //prints 65536

printf(“\n %u:”, *(array+1)); //literally translates to array[1]. Prints 6

P1

ComputerSystemsandNetworks

4

Spring2020

Page 5: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

PointersandFunctions:Callbyvaluevs.Callbyreference

Callbyvaluemain(){ a=5,b=6; update(a,b); printf(“%d”,a);}

update(int a, int b) { a=a-b;}

Thesearejustcopies.Nochangetooriginalvariables

Callbyreference(pointer)main(){ a=5,b=6; update(&a,&b); printf(“%d”,a);}

update(int *a,int *b) { *a=*a-*b;}

Modificationtoactualvariable

ComputerSystemsandNetworks

5

Spring2020

Page 6: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ìDynamicMemoryManagement

ComputerSystemsandNetworks

6

Spring2020

Page 7: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryAllocationwithmalloc()

ì  #include <stdlib.h>

ì  void * malloc(int size) ì  Allocateregioninmemory(aka“new”)ì  Argument:Sizeofregioninbytestoallocateì  Returnvalue:Pointertotheregion

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

ComputerSystemsandNetworks

7

Spring2020

Page 8: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryAllocationwithmalloc()

ì  void * calloc(int count, int size) ì  Basicallythesameasmalloc!

ì  Imagineyouwantanarrayofelements…

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

ComputerSystemsandNetworks

8

Spring2020

Page 9: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryAllocationwithmalloc()

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

ì  Notethatitmightmovetoanewaddress!

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

ì  Itmightbeatthesameaddressifyoumadeitsmallerì  Itmightbeatanewaddressifyoumadeitlarger

ComputerSystemsandNetworks

9

Spring2020

Page 10: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Malloc–1D

int *array; //array of integers

array = (int *)malloc(sizeof(int)*5);

60 64 68 72 76

array[0] array[1] array[2] array[3] array[4]

address:

value:

array(pointervariable)

value:????

pointeraddr:32

ComputerSystemsandNetworks

10

60

Spring2020

Page 11: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Malloc–2DAllocate4x5integers(Hintforlab4)

int **array; //a double pointer

array = (int **)malloc(sizeof(int *)*4);

for(i=0;i<4;i++) array[i] = (int *)malloc(sizeof(int)*5);

anarrayofintegerpointers

arrayofints

arrayofints

arrayofints

arrayofints

ComputerSystemsandNetworks

11

Spring2020

Page 12: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Malloc–3Dint ***array; //a triple pointer

anarrayofdoublepointers

amatrixofsinglepointers

a‘cuboid’ofintegers

ComputerSystemsandNetworks

12

Spring2020

Page 13: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Problem2

ì  Dynamicallyallocatespacefora3-Dcolorimageofwidth,w;height,h;colorchannel,c.Anypixelisaccessedasimage[height][width][c].

P2

ComputerSystemsandNetworks

13

Spring2020

Page 14: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ìMemoryManagementInternals

Spring2019ComputerSystemsandNetworks

14

Page 15: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Whoimplementedmalloc()?

ì  CStandardLibrary:#include <stdlib.h>

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

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

ComputerSystemsandNetworks

15

Spring2020

Page 16: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Wheredoesthemalloc()memorycomefrom?

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

(knownatcompile-time)

ComputerSystemsandNetworks

16

Spring2020

Page 17: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  malloc()outline:

1.  Callmalloc()andrequestmemory

2.  malloc()checksexistingheapsizeì  Sufficient?Updatebookkeepingtomarkspaceas

“used”andreturnaddresstoyourprogramì  Insufficient?

1.   Calloperatingsystemviabrk()/nmap()togrowtheheap(plusalittleextraforfuturerequests)

2.  Updatebookkeepingandreturnaddresstoyourprogram

ComputerSystemsandNetworks

17

Spring2020

Page 18: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

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

itsinternalbookkeepingstillthinksthatregionisused

ì  Willonlyberecovereduponterminatingprogramì  Operatingsystemwipesoutallthememoryallocated

toyourprocess(stack,heap,etc…)

ComputerSystemsandNetworks

18

Spring2020

Page 19: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  OScreatesvirtualmemoryspaceforprocesswhenstarted

ì  Regionishuge(full32or64bitspace)ì  Notfullymappedto

physicalmemoryì  Otherwiseyoucould

onlyfit1programinmemory

ComputerSystemsandNetworks

19

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

VirtualMemorySpacefornewprocess

Spring2020

Page 20: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  OSloadsintheprogramfromdisk

ì  “Text”regionì  Programcode

ì  “Data”regionì  Programfixed

data

ComputerSystemsandNetworks

20

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Spring2020

Page 21: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Stackcreatedtotrackprogramfunctioncallsandlocalvariables

ComputerSystemsandNetworks

21

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Spring2020

Page 22: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Heapcreatedtostoredynamicmemoryfrommalloc()andrelatedfunctions

ì  Nottoscale–thisunusedregionishuge!

ComputerSystemsandNetworks

22

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Spring2020

Page 23: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Programstartsrunning

ì  malloc() allocatessomememory

ComputerSystemsandNetworks

23

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Spring2020

Page 24: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Originalheapspaceeventuallyfillsup

ì  malloc()requestsadditionalspacefromthekernelbyusingbrk()systemcall

ComputerSystemsandNetworks

24

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Newspace

Spring2020

Page 25: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  free()deallocatesblocksfromtheheap

ComputerSystemsandNetworks

25

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Spring2020

Page 26: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  Programterminates

ì  OSexpungesentirevirtualaddressspaceì  Everythingis

deleted

ComputerSystemsandNetworks

26

0x0000000000000000

0xFFFFFFFFFFFFFFFF (32or64bit)

Text(Programcode)

Data(Programdata)

Stack

Heap

(Unused/unmappedvirtualmemory)

Spring2020

Page 27: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

BufferOverflowVulnerability

ì  Whatisabufferoverflowbug?ì  char buf1[8]="";

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

ì  Endupoverwritingtwocharactersbeyondbuf1!

27

ComputerSystemsandNetworks Spring2020

Page 28: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

BufferOverflowVulnerability

ì  Whyisabufferoverflowbugdangerous?

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

finishes?

ì  Ifappisrunningasadministrator,attackernowhasfullaccess!

28

ComputerSystemsandNetworks Spring2020

Page 29: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

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

target

ì  Willlearnatool(Valgrind)inLab5toanalyzeyourprogramanddetect/traceerrors

29

ComputerSystemsandNetworks Spring2020

Page 30: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

What’stheError?

ComputerSystemsandNetworks

30

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

Spring2020

Page 31: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

What’sthe(Potential)Error?

ComputerSystemsandNetworks

31

char *a = malloc(128*sizeof(char)); dataLen = <some value...> // Copy “dataLen” bytes // starting at *data to *a memcpy(a, data, dataLen);

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

Spring2020

Page 32: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

What’stheError?

ComputerSystemsandNetworks

32

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

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

Spring2020

Page 33: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

What’stheError?

ComputerSystemsandNetworks

33

int *get_ii() { int ii = 2; // Local stack variable return &ii; } main() { int *ii; ii = get_ii(); ... Do stuff using ii pointer } http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

Spring2020

Page 34: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ComputerSystemsandNetworks

34

http://xkcd.com/371/

Spring2020

Page 35: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  What’saNULLpointer?ì  Pointervalueis0x000000000ì  Meaningisthatthepointerisnotpointing

anywhere

ì  WhathappensifyoudereferenceaNULLpointer?ì  Tellingthecomputertoreadfrom(orwrite)tothe

valuestoredinthepointer,whichis0x000000000ì  Behaviorundefinedandgenerallyunpleasanton

variouscomputersystems

ComputerSystemsandNetworks

35

Spring2020

Page 36: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

MemoryManagement

ì  “Segfault”=SegmentationFault

ì  Yourprogramtriedtoreadorwriteavirtualmemoryaddressthatisnotallowedì  Triedtoreadmemoryoutsideofprogrambounds?ì  Triedtowriteread-onlymemoryregions?(usedfor

programdata)

ì  “Segmentation”wasthenameofanoldsystem(backbeforeIntel386processors)usedtodividephysicalcomputermemoryintomanyvirtualaddressregions,oneperapplicationprocessì  TheSegfaultnamestuckeventhoughwenowusepaging

tomanagevirtualmemory

ComputerSystemsandNetworks

36

Spring2020

Page 37: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ìStructures

ComputerSystemsandNetworks

37

Spring2020

Page 38: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Structures

ComputerSystemsandNetworks

38

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

Usefulwaytogrouprelatedvariables!

Spring2020

Page 39: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Problem3

ComputerSystemsandNetworks

39

P3

Declare a structure called board that contains: •  a double character pointer matrix •  two integer variables height and width denoting the

number of rows and columns in the matrix. Inside main, do the following: 1. Create a structure object called myboard,

initialize matrix to NULL, set height to 7 and width to 7 2. Dynamically allocate matrix to hold height x

width elements

Spring2020

Page 40: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Problem4

ComputerSystemsandNetworks

40

P4

ContinuewiththecodefromProblem3.Traversethe2Dmatrixofdimensionsheight(rows)andwidth(columns).WriteaCsnippettofindthefirstinstanceoflowercaseletter‘e’.Obtainallthelettersstartingfrom‘e’placeddiagonallydownwardsandtotherightinthismatrix.Storethelettersina1Darray,buffer.Makesurethatbufferisoflargeenoughsizetocontainalloftheletters.

Spring2020

Page 41: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

Problem5

ComputerSystemsandNetworks

41

P5

ContinuewiththecodefromProblem3.free()isactuallyareverseoperationofmalloc.Thestepsyouuseforfreeareoppositeofthestepsformalloc.Freethedynamicallyallocated2DmatrixyoucreatedinProblem3.

Spring2020

Page 42: C Programming 2 - University of the Pacific · Pointer Arithmetic ì Only addition and subtraction are allowed with pointers ì All pointers increase and decrease by the length of

ComputerSystemsandNetworks

42

You’rereadyto

BeginLab4!

Spring2020