68
1 Uri Dekel Carnegie Mellon University [email protected] Introduction to Pointers Introduction to Pointers and and Memory Management in C Memory Management in C

Introduction to pointers and memory management in C

Embed Size (px)

DESCRIPTION

Slides for a 30 minutes tutorial on pointers in C

Citation preview

Page 1: Introduction to pointers and memory management in C

1

Uri DekelCarnegie Mellon University

[email protected]

Introduction to Pointers andIntroduction to Pointers and Memory Management in C Memory Management in C

Page 2: Introduction to pointers and memory management in C

2

AssumptionsAssumptions

Audience familiar with:VariablesControl structuresFunction callsArrays and strings

Not familiar withComputer memoryImplementation of variables and function calls

Intro to Pointers and Memory in C

Page 3: Introduction to pointers and memory management in C

3

TopicsTopics

Computer memory in generalImplementation of variables and function calls

Pointers and overcoming function limitations

Pointer arithmetic and arraysNeed and risks of dynamic memory allocation

Intro to Pointers and Memory in C

Page 4: Introduction to pointers and memory management in C

4

FocusFocus

Understanding of concepts and techniques

Reasoning for use of specific techniques

Caveats to watch out for

Intro to Pointers and Memory in C

Page 5: Introduction to pointers and memory management in C

5

Note on C versionsNote on C versions

Presented material is in C90 (old “Ansi C”)Supported by nearly all compilersBasis for most legacy code

Newer C’99 and later is differentAllows some C++ conventionsIntroduces new featuresNot fully supported by all compilers

Intro to Pointers and Memory in C

Page 6: Introduction to pointers and memory management in C

6

Introduction to Computer Memory

Intro to Pointers and Memory in C Background

DynamicPointers

Page 7: Introduction to pointers and memory management in C

7

Why do we need memory?Why do we need memory?

CPU operates on data in a handful of registers

Not enough for most applicationsMemory is vast collection of “value

holders”Values copied to/from registers

Background

DynamicPointersIntro to Pointers and Memory in C

Page 8: Introduction to pointers and memory management in C

8

Memory needs to be organizedMemory needs to be organized

Must be able to locate previously stored valueCan’t rely on actual value

Programmers see linear address space

Typical address space is vast32bit or 64bit

Background

DynamicPointersIntro to Pointers and Memory in C

Page 9: Introduction to pointers and memory management in C

9

What do we do with multi-byte What do we do with multi-byte values?values?Size of cell is limited

Typically byte (8 bits, 0—255)Spread values in contiguous cells

Only need to know starting address and size

Background

DynamicPointersIntro to Pointers and Memory in C

Page 10: Introduction to pointers and memory management in C

10

What do we do with multi-byte What do we do with multi-byte values?values?Breakup of large values must be consistent with their reassemblyWhere do we store the more-significant digits?

Background

DynamicPointersIntro to Pointers and Memory in C

Page 11: Introduction to pointers and memory management in C

11

Virtual MemoryVirtual Memory

Modern OSs provide separate address space to processesCertain logical addresses mapped to physical addresses

Mechanism transparentOverlapping addresses do not interfere

Not every address is mapped!

Background

DynamicPointersIntro to Pointers and Memory in C

Page 12: Introduction to pointers and memory management in C

12

Variables and Function Calls in C

Background

DynamicPointersIntro to Pointers and Memory in C

Page 13: Introduction to pointers and memory management in C

13

VariablesVariables

A symbolic name for a specific memory locationCan read and write contentsGuaranteed to exist every time it is used

Type used to reassemble and interpret valueHow many cells? How value is broken down

13

Background

DynamicPointersIntro to Pointers and Memory in C

Page 14: Introduction to pointers and memory management in C

14

Automatic variablesAutomatic variables

Declared at a beginning of a blockLifetime and scope correspond to block

Background

DynamicPointersIntro to Pointers and Memory in C

Page 15: Introduction to pointers and memory management in C

15

Allocating space for variablesAllocating space for variables

Variables are allocated space on stackLast-In-First-Out structureHas a fixed base and grows “up” or “down”

Newer variables allocated “above” earlierNewer variables “die” before olderStack resides in specific memory segment

Background

DynamicPointersIntro to Pointers and Memory in C

Page 16: Introduction to pointers and memory management in C

16

Program code and memoryProgram code and memory

Our program (“code”) is stored in memoryDedicated “code segment”Every instruction has an addressEvery function has an address

Most instructions are contiguousCPU uses instruction pointer (IP) register for next address to executeExecution typically sequentialIP changes on branches

Background

DynamicPointersIntro to Pointers and Memory in C

Page 17: Introduction to pointers and memory management in C

17

Stack example (In function)Stack example (In function)

Background

DynamicPointersIntro to Pointers and Memory in C

Page 18: Introduction to pointers and memory management in C

18

Stack example (In function)Stack example (In function)

Background

DynamicPointersIntro to Pointers and Memory in C

Page 19: Introduction to pointers and memory management in C

19

What happens in function call?What happens in function call?

Copies of argument values pushed into stack

Return address pushed into stack

CPU IP aimed at beginning of function block

Background

DynamicPointersIntro to Pointers and Memory in C

Page 20: Introduction to pointers and memory management in C

20

What happens in function call?What happens in function call?

Background

DynamicPointersIntro to Pointers and Memory in C

Page 21: Introduction to pointers and memory management in C

21

Returning from functions…Returning from functions…

All automatic variables of function are poppedReturn address is poppedAll passed arguments are poppedIP aimed at next instruction to execute in

original functionReturn value in register or stack

Background

DynamicPointersIntro to Pointers and Memory in C

Page 22: Introduction to pointers and memory management in C

22

Returning from functions…Returning from functions…

Background

DynamicPointersIntro to Pointers and Memory in C

Page 23: Introduction to pointers and memory management in C

23

Attempting to write a swap Attempting to write a swap function…function…

Background

DynamicPointersIntro to Pointers and Memory in C

Page 24: Introduction to pointers and memory management in C

24

Attempting to write a swap Attempting to write a swap function…function…

Background

DynamicPointersIntro to Pointers and Memory in C

Page 25: Introduction to pointers and memory management in C

25

Attempting to write a swap Attempting to write a swap function…function…

Background

DynamicPointersIntro to Pointers and Memory in C

Page 26: Introduction to pointers and memory management in C

26

Attempting to write a swap Attempting to write a swap function…function…

Background

DynamicPointersIntro to Pointers and Memory in C

Page 27: Introduction to pointers and memory management in C

27

Pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 28: Introduction to pointers and memory management in C

28

Why pass-by-pointer?Why pass-by-pointer?

Functions always pass values by copying (pass-by-value)

They return a single value by copyingChanges to arguments in invoked functions have

NO IMPACTon corresponding variables in invoking function

To change, we must “break through” to earlier stack locations.

Solution: 1) Pass address of value holder represented by

variable2) Use that address to write directly into the

value holderBackground DynamicPointer

sIntro to Pointers and Memory in C

Page 29: Introduction to pointers and memory management in C

29

PointersPointers

A pointer is a variable!It has an address and stores a valueBut the value can be interpreted as an address

X myX – declare variable of type XX* pX – declare pointer to value of type

XPointer size depends on address space, not type!

Background DynamicPointers

Intro to Pointers and Memory in C

Page 30: Introduction to pointers and memory management in C

30

Assigning values to pointersAssigning values to pointers

Arbitrary numeric valuesAddress of variablesValues of other pointersAddress of functions (outside our scope)Caveat: Avoid pointing at temporaries!

Background DynamicPointers

Intro to Pointers and Memory in C

Page 31: Introduction to pointers and memory management in C

31

Dereferencing pointersDereferencing pointers

Accessing the pointed-to memory cellIf pX is pointer, (*pX) is the valueRoughly, var is equivalent to (*(&var))Can serve as an lvalue! (can assign into it)

Background DynamicPointers

Intro to Pointers and Memory in C

Page 32: Introduction to pointers and memory management in C

32

Implementing SwapImplementing Swap

Background DynamicPointers

Intro to Pointers and Memory in C

Page 33: Introduction to pointers and memory management in C

33

Implementing SwapImplementing Swap

Background DynamicPointers

Intro to Pointers and Memory in C

Page 34: Introduction to pointers and memory management in C

34

Implementing SwapImplementing Swap

Background DynamicPointers

Intro to Pointers and Memory in C

Page 35: Introduction to pointers and memory management in C

35

Implementing SwapImplementing Swap

Background DynamicPointers

Intro to Pointers and Memory in C

Page 36: Introduction to pointers and memory management in C

36

Caveat – Uninitialized pointersCaveat – Uninitialized pointers

Uninitialized pointers can contain junk

Dereferencing leads to random addressData overwrites, segmentation faults, etc.

Background DynamicPointers

Intro to Pointers and Memory in C

Page 37: Introduction to pointers and memory management in C

37

Caveat – NULL pointersCaveat – NULL pointers

Pointers to NULL should not be dereferenced

Equivalent to accessing address 0Access may result in “Bus Error” on UNIX

Background DynamicPointers

Intro to Pointers and Memory in C

Page 38: Introduction to pointers and memory management in C

38

Caveats – Dangling referencesCaveats – Dangling references

Avoid returning pointer to automatic vars

Don’t keep pointers to vars in inner blocks

Background DynamicPointers

Intro to Pointers and Memory in C

Page 39: Introduction to pointers and memory management in C

39

Casting pointersCasting pointers

Converting between pointer types is riskyCompiler will warn – Coercion possible

Background DynamicPointers

Intro to Pointers and Memory in C

Page 40: Introduction to pointers and memory management in C

40

Void*Void*

Pointer type used to represent addresses without any type information

Shouldn’t be dereferencedProgrammer responsible for coercion

Background DynamicPointers

Intro to Pointers and Memory in C

Page 41: Introduction to pointers and memory management in C

41

Const pointersConst pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 42: Introduction to pointers and memory management in C

42

Pointers to pointersPointers to pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 43: Introduction to pointers and memory management in C

43

Pointers to pointersPointers to pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 44: Introduction to pointers and memory management in C

44

Pointers to pointersPointers to pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 45: Introduction to pointers and memory management in C

45

Pointers to pointersPointers to pointers

Background DynamicPointers

Intro to Pointers and Memory in C

Page 46: Introduction to pointers and memory management in C

46

Pointer ArithmeticPointer Arithmetic

C permits addition/subtraction on pointersIncrements correspond to size of type value

Effective with contiguous set of variables

Background DynamicPointers

Intro to Pointers and Memory in C

Page 47: Introduction to pointers and memory management in C

47

Pointers to array elementsPointers to array elements

Pointers can aimat address of array elements

Refer to other elements withpointer arithmetic

Background DynamicPointers

Intro to Pointers and Memory in C

Page 48: Introduction to pointers and memory management in C

48

Array variable often treated as ptr to 1st elementActually not a pointerComputes into an rvalue

for assignment to pointer

Passable to function that takes pointer or array

Not reassignableSizeof(ar) returns array

size

The array “Variable”The array “Variable”

Background DynamicPointers

Intro to Pointers and Memory in C

Page 49: Introduction to pointers and memory management in C

49

Dynamic Memory Allocation

Background DynamicPointersIntro to Pointers and Memory in C

Page 50: Introduction to pointers and memory management in C

50

Why do we need to allocate Why do we need to allocate memory?memory?Size of data may not be known in

advanceMay depend on user input

e.g., Input N, then get N numbers, then present sorted

May depend on result of calculationSize may change over time

e.g., Increase canvas size or number of pages

Intro to Pointers and Memory in C Background DynamicPointers

Page 51: Introduction to pointers and memory management in C

51

Why do we need to allocate Why do we need to allocate memory?memory?Global and automatic arrays can only be declared with compile-time constant size(Relaxed in C99)

Intro to Pointers and Memory in C Background DynamicPointers

Page 52: Introduction to pointers and memory management in C

52

Why do we need to allocate Why do we need to allocate memory?memory?We want to control lifetime of data

stored over timeLive after function endsDie before program terminates

Basis for most data structures

Intro to Pointers and Memory in C Background DynamicPointers

Page 53: Introduction to pointers and memory management in C

53

How do we allocate memory?How do we allocate memory?

void *malloc(size_t size);Submits request to allocate contiguous block of

given size.Size often specified as n*sizeof(type)If failed, returns NULLIf valid, returns void pointer to new memory areaProgrammer converts into pointer to first

elementPointer arithmetic or subscripts access rest of

spaceNo bounds checking!

NULL otherwiseIntro to Pointers and Memory in C Background DynamicPointers

Page 54: Introduction to pointers and memory management in C

54

The heapThe heap

A memory area provided to the process for allocating dataOften limited

Runtime tracks where all memory is allocatedEvery allocation is contiguous

Possibility of fragmentation even if enough total free space

No way to check in advance

Intro to Pointers and Memory in C Background DynamicPointers

Page 55: Introduction to pointers and memory management in C

55

Allocated memory must be freed!Allocated memory must be freed!

Programmer responsible for releasing dynamically allocated memory ASAP.Use free() operation

void free(void *ptr);System will know how much space to clear

Failure to free causes memory leak

Intro to Pointers and Memory in C Background DynamicPointers

Page 56: Introduction to pointers and memory management in C

56

Malloc/Free exampleMalloc/Free example

Intro to Pointers and Memory in C Background DynamicPointers

Page 57: Introduction to pointers and memory management in C

57

free() caveatsfree() caveats

Do not free a pointer prematurelyMake sure it will not be accessed again via other pointer!

All other pointers are dangling references

Intro to Pointers and Memory in C Background DynamicPointers

Page 58: Introduction to pointers and memory management in C

58

free() caveatsfree() caveats

Once pointer to memory is lost, no way to free it

Do not release pointer to middle of allocated region

Intro to Pointers and Memory in C Background DynamicPointers

Page 59: Introduction to pointers and memory management in C

59

free() caveatsfree() caveats

Freeing the same memory twiceFreeing an automatic variable

Intro to Pointers and Memory in C Background DynamicPointers

Page 60: Introduction to pointers and memory management in C

60

Summary of covered topicsSummary of covered topics

MemoryAddress space necessary to understand pointers

Storage of large valuesImplementation of variables and calls

Lifetime and effect on pointer validityNeed for pointers

Pointers and their risksPointer arithmetic and relation to arraysNeed and risk of dynamic allocation

Intro to Pointers and Memory in C Background DynamicPointers

Page 61: Introduction to pointers and memory management in C

61

Questions?

Page 62: Introduction to pointers and memory management in C

62

Backup materials

Intro to Pointers and Memory in C

Page 63: Introduction to pointers and memory management in C

63

Topics not coveredTopics not covered

Pointers to pointersFunction pointersStructsFar pointers

Page 64: Introduction to pointers and memory management in C

64

Do not rely on stack organization!Do not rely on stack organization!

Page 65: Introduction to pointers and memory management in C

65

Pointers can be comparedPointers can be compared

Page 66: Introduction to pointers and memory management in C

66

Caveats – Dangling referencesCaveats – Dangling references

Do not keep pointers to dying variables

Page 67: Introduction to pointers and memory management in C

67

Null-terminated stringsNull-terminated strings

Strings: Array of chars terminated by ‘\0’ or 0.String can take less space than actual array

sizeSince \0 can come early…

Missing the \0 will lead many functions past allocated memory

Storage depends on actual assignment

Page 68: Introduction to pointers and memory management in C

68

Global VariablesGlobal Variables

Variables can be declared outside functionsAccessible from everywhereInitialized before main() startedLive until program terminatesFunction static variables can be thought of as

global