46
Pointers and Memory 9/29/16

Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersandMemory9/29/16

Page 2: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Recall:Allocating(Heap)Memory

• ThestandardClibrary(#include<stdlib.h>)includesfunctionsforallocatingmemory

void *malloc(size_t size)• Allocatesize bytesontheheapandreturnapointertothebeginningofthememoryblock

void free(void *ptr)• Releasethemalloc()ed blockofmemorystartingatptr backtothesystem

Page 3: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Whatdoyouexpecttohappentothe100-bytechunkifwedothis?//Whathappenstothese100bytes?

int *ptr = malloc(100);

ptr = malloc(2000);

A. The100-bytechunkwillbelost.

B. The100-bytechunkwillbeautomaticallyfreed(garbagecollected)bytheOS.

C. The100-bytechunkwillbeautomaticallyfreed(garbagecollected)byC.

D. The100-bytechunkwillbethefirst100bytesofthe2000-bytechunk.

E. The100-bytechunkwillbeaddedtothe2000-bytechunk(2100bytestotal).

Page 4: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MemoryLeak

• Memorythatisallocated,andnotfreed,forwhichthereisnolongerapointer.

• Inmanylanguages(Java,Python,…),thismemorywillbecleanedupforyou.• “Garbagecollector”findsunreachablememoryblocks,freesthem.• Cdoesn’tdoesNOTdothisforyou!

Page 5: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Whydoesn’tCdogarbagecollection?A. It’simpossibleinC.

B. Itrequiresalotofresources.

C. Itmightnotbesafetodoso.(breakprograms)

D. Ithadn’tbeeninventedatthetimeCwasdeveloped.

E. Someotherreason.

Page 6: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MemoryBookkeeping• Tofreeachunk,youMUSTcallfreewiththesamepointerthatmalloc gaveyou.(oracopy)

• ThestandardClibrarykeepstrackofthechunksthathavebeenallocatedtoyourprogram.• Thisiscalled“metadata”– dataaboutyourdata.

• Wait,wheredoesitstorethatinformation?• It’snotlikeitcanusemalloc()togetmemory…

Page 7: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Whereshouldwestorethismetadata?A. IntheCPU

B. Inmainmemory

C. Ontheharddrive

D. Somewhereelse

Page 8: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MetadataHeap

int *iptr = malloc(8);

Page 9: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MetadataHeap

FirstByte

… … …

… … … LastByte

int *iptr = malloc(8);

Page 10: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MetadataHeap

Meta Data

Meta Data

FirstByte

… … …

… … … LastByte

int *iptr = malloc(8);

• CLibrary:“Letmerecordthisallocation’sinfohere.”• Sizeofallocation• Maybeotherinfo

Page 11: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MetadataHeap

Meta Data Meta Data

FirstByte

… … …

… … … LastByte

Meta Data Meta Data

Other

Data

int *iptr = malloc(8);

• Forallyouknow,therecouldbeanotherchunkafteryours.

Page 12: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

MetadataHeap

Meta Data Meta Data

FirstByte

… … …

… … … LastByte

Meta Data Meta Data

Other

Data

int *iptr = malloc(8);

• Takeaway:veryimportantthatyoustaywithinthememorychunksyouallocate.

• Ifyoucorruptthemetadata,youwillgetweirdbehavior.

Valgrind isyournewbestfriend.

Page 13: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

• “Whydidyouallocate8bytesforanint pointer?Isn’tanint only4bytes?”• int *iptr = malloc(8);

• Recall:anarrayvariableactslikeapointertoablockofmemory.Thenumberin[]isanoffsetfrombucket0,thefirstbucket.

• Wecantreatpointersinthesameway!

Page 14: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Heap

int *iptr = NULL;

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

PointersasArrays

Page 15: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

1st integer

2nd integer

3rd integer

4th integer

int *iptr = NULL;

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

Page 16: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

1st integer

2nd integer

3rd integer

4th integer

int *iptr = NULL;

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

TheCcompilerknowshowbiganintegeris.

Asanalternativewayofdereferencing,youcanuse[]’slikeanarray.

TheCcompilerwilljumpaheadtherightnumberofbytes,basedonthetype.

Page 17: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

iptr[0]

iptr[1]

iptr[2]

iptr[3]

int *iptr = NULL;

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

Page 18: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

iptr[0]

iptr[1]

iptr[2]

iptr[3]

int *iptr = NULL;

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

iptr[2] = 7;

1.Startfromthebaseofiptr.

Page 19: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

iptr[0]

iptr[1]

iptr[2]

iptr[3]

int *iptr = NULL;

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

iptr[2] = 7;

1.Startfromthebaseofiptr.

2.Skipforwardbythesizeoftwoints.

Page 20: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

Heap

iptr[0]

iptr[1]

7

iptr[3]

int *iptr = NULL;

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

iptr[2] = 7;

1.Startfromthebaseofiptr.

2.Skipforwardbythesizeoftwoints.

3.Treattheresultasanint.(Accessthememorylocationlikeatypicaldereference.)

Page 21: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointersasArrays

• Thisisoneofthemostcommonwaysyou’llusepointers:• Youneedtodynamicallyallocatespaceforacollectionofthings(ints,structs,whatever).• Youdon’tknowhowmanyatcompiletime.

float *student_gpas = NULL;

student_gpas = malloc(n_students * sizeof(int));

student_gpas[0] = …;

student_gpas[1] = …;

Page 22: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArithmetic

• Additionandsubtractionworkonpointers.

• Cautomaticallyincrementsbythesizeofthetypethat’spointedto.

Page 23: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArithmetic

Heap

1st integer

2nd integer

3rd integer

4th integer

int *iptr = NULL;

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

Page 24: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArithmetic

Heap

1st integer

2nd integer

3rd integer

4th integer

int *iptr = NULL;

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

int *iptr2 = iptr + 3;

Skipaheadby3timesthesizeofiptr’stype(integer,size:4bytes).

Page 25: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Otherusesforpointers…

1. Allowingafunctiontomodifyavariable.

2. Allowingafunctiontoreturnmemory.

3. Manymore…

Page 26: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

FunctionArguments

• Argumentsarepassedbyvalue• Thefunctiongetsaseparatecopy ofthepassedvariable

int func(int a, int b) {

a = a + 5;return a - b;

}

int main() {

int x, y; // declare two integersx = 4;

y = 7;y = func(x, y);printf(“%d, %d”, x, y);

}

Stack

main:x:

y:

func:a:

b:

4

7

4

7

4

7

Page 27: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

FunctionArguments

• Argumentsarepassedbyvalue• Thefunctiongetsaseparatecopy ofthepassedvariable

int func(int a, int b) {

a = a + 5;return a - b;

}

int main() {

int x, y; // declare two integersx = 4;

y = 7;y = func(x, y);printf(“%d, %d”, x, y);

}

Stack

main:x:

y:

4

7

4

7

Itdoesn’tmatterwhatfuncdoeswithaandb.Thevalueofxinmaindoesn’tchange.

Page 28: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

FunctionArguments

• Argumentscanbepointers!• Thefunctiongetstheaddressofthepassedvariable!

void func(int *a) {*a = *a + 5;

}

int main() {int x = 4;

func(&x);printf(“%d”, x);

}

Stack

main:

Page 29: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArguments

• Argumentscanbepointers!• Thefunctiongetstheaddressofthepassedvariable!

void func(int *a) {*a = *a + 5;

}

int main() {int x = 4;

func(&x);printf(“%d”, x);

}

Stack

main:

x: 4

Page 30: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArguments

• Argumentscanbepointers!• Thefunctiongetstheaddressofthepassedvariable!

void func(int *a) {*a = *a + 5;

}

int main() {int x = 4;

func(&x);printf(“%d”, x);

}

Stack

main:

func:a:

x: 4

Page 31: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArguments

• Argumentscanbepointers!• Thefunctiongetstheaddressofthepassedvariable!

void func(int *a) {*a = *a + 5;

}

int main() {int x = 4;

func(&x);printf(“%d”, x);

}

Stack

main:

func:a:

x: 9

Dereferencepointer,setvaluethatapointsto.

Page 32: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerArguments

• Argumentscanbepointers!• Thefunctiongetstheaddressofthepassedvariable!

void func(int *a) {*a = *a + 5;

}

int main() {int x = 4;

func(&x);printf(“%d”, x);

}

Stack

main:

x: 9

Prints:9

Haven’tweseenthissomewherebefore?

Page 33: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Readfile Library

• We’veseensawthisinlab2and4withread_intandread_float.• Thisiswhyyouneededan&.• e.g.,

int value;status_code = read_int(&value);

• You’reaskingread_int tomodifyaparameter,soyougiveitapointertothatparameter.• read_int willdereferenceitandsetit.

Page 34: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Otherusesforpointers…

1. Allowingafunctiontomodifyavariable.

2. Allowingafunctiontoreturnmemory.

3. Manymore…

Page 35: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Canyoureturnanarray?

• Supposeyouwantedtowriteafunctionthatcopiesanarrayofintegers.

copy_array(int array[], int len) {int result[len];for(int i=0; i<len; i++)

result[i] = array[i];return result;

}Thisisaterribleidea.(Don’tworry,compilerwontletyoudothisanyway.)

Howmanybugscanyoufind?A=1,B=2,…

Page 36: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Considerthememory…

copy_array5(int array[]) {

int result[5];

for(int i=0; i<5; i++)

result[i] = array[i];

return result;

}

(In main):

copy = copy_array(…)

copy_array5:

main:

copy:

result

Page 37: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Considerthememory…

main:

copy:

resultresult

copy_array5(int array[]) {

int result[5];

for(int i=0; i<5; i++)

result[i] = array[i];

return result;

}

(In main):

copy = copy_array(…)

copy_array5:

Page 38: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Considerthememory…

copy_array5(int array[]) {

int result[5];

for(int i=0; i<5; i++)

result[i] = array[i];

return result;

}

(In main):

copy = copy_array(…)main:

copy:

Whenwereturnfromcopy_array,itsstackframeisgone!

Leftwithapointertonowhere.

Page 39: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

UsingtheHeapint *copy_array(int array[], int len) {

int *result = malloc(len * sizeof(int));

for(int i=0; i<len; i++)

result[i] = array[i];

return result;

}

0x0

0xFFFFFFFF

Operatingsystem

Stack

TextDataHeap

result:

malloc memoryisontheheap.

Doesn’tmatterwhathappensonthestack(functioncalls,returns,etc.)

Page 40: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Otherusesforpointers…1. Allowingafunctiontomodifyavariable.

2. Allowingafunctiontoreturnmemory.

• Thesearebothverycommon.Youshouldbeusingtheminlab4.

3. Manymore…• Avoidingcopies(structs …comingupshortly)• Sharingbetweenthreads(endofthesemester)

Page 41: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerstoPointers• Whystopatjustonepointer?

int **double_iptr;

• “Apointertoapointertoanint.”• Dereferenceonce:pointertoanint• Dereferencetwice:int

• Commonlyusedto:• Allowafunctiontomodifyapointer(datastructures)• Dynamicallycreateanarrayofpointers.• (Programcommandlineargumentsusethis.)

int main(int argv, char** argv)

Page 42: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Recall:structs ontheheapstruct student {

char name[40];

int age;

double gpa;

}

struct student *bob = NULL;

bob = malloc(sizeof(struct student));

Page 43: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

PointerstoStructs -> operator

struct student *bob = NULL;

bob = malloc(sizeof(struct student));

(*bob).age = 20;

bob->gpa = 3.5;

The-> operatorisashortcuttodoadereference(*)andafieldaccess(.).

Page 44: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Arraysvs.Pointers

Howarearrayvariablesdifferentfrompointervariables?Thinkofasmanydifferencesasyoucan.

• Declareddifferently.int arr[5];int *ptr;ptr = malloc(5 * sizeof(int));

• Storeddifferently• Stack• Heap

• PointersareLvalues

Page 45: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Lvalues

• Anythingthatcanbeontheleft-handsideofanassignment.• Examples:• int• float• Structs (e.g.struct student)• pointers

• Arraysarenotlvalues.Youcan’tmoveadifferentaddressintoanarrayvariable.

Page 46: Pointers and Memory - Swarthmore Collegebryce/cs31/f16/slides/w05b_memory.pdf · Memory Leak • Memory that is allocated, and not freed, for which there is no longer a pointer. •

Struct Parameters:PassbyValue:void test(struct student s1){

s1.age = 20;s1.name[0] = ‘X’;

}int main() {struct student jo;strcpy(jo.name, “Jo”);jo.age = 18;test(jo);

}

test:

main:

STACK

Q1: What is the value of the argument jo?

Q2: What value does param s1 get?Q3: Draw the StackQ4: What is value of jo after the

function call?