Sei sulla pagina 1di 68

Introduction to Pointers and Memory Management in C

Uri Dekel Carnegie Mellon University udekel@cs.cmu.edu

Assumptions
Audience familiar with: Variables Control structures Function calls Arrays and strings Not familiar with
Computer memory

Implementation of variables and

function calls
2
Intro to Pointers and Memory in C

Topics
Computer memory in general
Implementation of variables and function

calls Pointers and overcoming function limitations Pointer arithmetic and arrays Need and risks of dynamic memory allocation
3
Intro to Pointers and Memory in C

Focus
Understanding of concepts and

techniques Reasoning for use of specific techniques Caveats to watch out for

Intro to Pointers and Memory in C

Note on C versions
Presented material is in C90 (old

Ansi C) Supported by nearly all compilers Basis for most legacy code
Newer C99 and later is different
Allows some C++ conventions Introduces new features Not fully supported by all compilers
5
Intro to Pointers and Memory in C

Introduction to Computer Memory

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Why do we need memory?


CPU operates on data in a handful of registers Not enough for most applications
Memory is vast collection of value holders

Values copied to/from registers

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Memory needs to be organized


Must be able to locate previously

stored value Cant rely on actual value Programmers see linear address space Typical address space is vast 32bit or 64bit
8
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

What do we do with multi-byte values?


Size of cell is limited
Typically byte (8 bits, 0255)

Spread values in contiguous cells Only need to know starting address and

size

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

What do we do with multi-byte values?


Breakup of large values must be

consistent with their reassembly Where do we store the more-significant digits?

10

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Virtual Memory
Modern OSs provide separate address space

to processes Certain logical addresses mapped to physical addresses Mechanism transparent Overlapping addresses do not interfere Not every address is mapped!

11

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Variables and Function Calls in C

12

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Variables
A symbolic name for a specific memory

location Can read and write contents Guaranteed to exist every time it is used Type used to reassemble and interpret value How many cells? How value is broken down 13
13
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Automatic variables
Declared at a beginning of a block Lifetime and scope correspond to block

14

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Allocating space for variables


Variables are allocated space on stack
Last-In-First-Out structure Has a fixed base and grows up or down

Newer variables allocated above earlier Newer variables die before older
Stack resides in specific memory segment

15

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Program code and memory


Our program (code) is stored in memory Dedicated code segment
Every instruction has an address Every function has an address

Most instructions are contiguous

CPU uses instruction pointer (IP) register

for next address to execute


Execution typically sequential

IP changes on branches
16
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Stack example (In function)

17

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Stack example (In function)

18

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

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

19

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

What happens in function call?

20

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Returning from functions


All automatic variables of function are popped
Return address is popped

All passed arguments are popped IP aimed at next instruction to execute in original

function Return value in register or stack

21

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Returning from functions

22

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Attempting to write a swap function

23

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Attempting to write a swap function

24

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Attempting to write a swap function

25

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Attempting to write a swap function

26

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers

27

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Why pass-by-pointer?
Functions always pass values by copying (pass-by-

value) They return a single value by copying Changes to arguments in invoked functions have NO IMPACT on corresponding variables in invoking function To change, we must break through to earlier stack locations.
Solution: 1) Pass address of value holder represented by variable 2) Use that address to write directly into the value
28
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

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

address X myX declare variable of type X X* pX declare pointer to value of type X Pointer size depends on address space, not type!

29

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Assigning values to pointers


Arbitrary numeric values Address of variables Values of other pointers Address of functions (outside our scope) Caveat: Avoid pointing at temporaries!

30

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Dereferencing pointers

Accessing the pointed-to memory cell


If pX is pointer, (*pX) is the value Roughly, var is equivalent to (*(&var)) Can serve as an lvalue! (can assign into it)

31

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Implementing Swap

32

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Implementing Swap

33

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Implementing Swap

34

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Implementing Swap

35

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Caveat Uninitialized pointers


Uninitialized pointers can contain junk
Dereferencing leads to random address

Data overwrites, segmentation faults,

etc.

36

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Caveat NULL pointers


Pointers to NULL should not be

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

37

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Caveats Dangling references


Avoid returning pointer to automatic

vars

Dont keep pointers to vars in inner

blocks
38
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Casting pointers

Converting between pointer types is risky


Compiler will warn Coercion possible

39

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Void*
Pointer type used to represent addresses without any type information Shouldnt be dereferenced Programmer responsible for coercion

40

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Const pointers

41

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers to pointers

42

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers to pointers

43

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers to pointers

44

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers to pointers

45

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointer Arithmetic
C permits addition/subtraction on pointers Increments correspond to size of type value
Effective with contiguous set of variables

46

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Pointers to array elements


Pointers can aim

at address of array elements Refer to other elements with pointer arithmetic

47

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

The array Variable


Array variable often

treated as ptr to 1st element


Actually not a pointer Computes into an rvalue

for assignment to pointer Passable to function that takes pointer or array Not reassignable Sizeof(ar) returns array size
48
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Dynamic Memory Allocation

49

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Why do we need to allocate memory?


Size of data may not be known in advance May depend on user input e.g., Input N, then get N numbers, then present sorted
May depend on result of calculation Size may change over time e.g., Increase canvas size or number of pages

50

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Why do we need to allocate memory?


Global and automatic arrays can only be

declared with compile-time constant size


(Relaxed in C99)

51

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Why do we need to allocate memory?


We want to control lifetime of data stored over

time
Live after function ends
Die before program terminates

Basis for most data structures

52

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

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 NULL If valid, returns void pointer to new memory area Programmer converts into pointer to first element Pointer arithmetic or subscripts access rest of space No bounds checking!
NULL otherwise
53
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

The heap
A memory area provided to the process for allocating

data Often limited Runtime tracks where all memory is allocated Every allocation is contiguous Possibility of fragmentation even if enough total free space No way to check in advance

54

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

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

55

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Malloc/Free example

56

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

free() caveats
Do not free a pointer prematurely
Make sure it will not be accessed again via

other pointer! All other pointers are dangling references

57

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

free() caveats
Once pointer to memory is lost, no way to free

it Do not release pointer to middle of allocated region

58

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

free() caveats
Freeing the same memory twice Freeing an automatic variable

59

Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Summary of covered topics


Memory Address space necessary to understand

pointers Storage of large values Implementation of variables and calls Lifetime and effect on pointer validity Need for pointers Pointers and their risks Pointer arithmetic and relation to arrays Need and risk of dynamic allocation
60
Intro to Pointers and Memory in C

Background

Pointers

Dynamic

Questions?

61

Backup materials

62

Intro to Pointers and Memory in C

Topics not covered


Pointers to pointers Function pointers Structs Far pointers

63

Do not rely on stack organization!

64

Pointers can be compared

65

Caveats Dangling references


Do not keep pointers to dying variables

66

Null-terminated strings
Strings: Array of chars terminated by \0 or 0.
String can take less space than actual array size

Since \0 can come early Missing the \0 will lead many functions past allocated

memory Storage depends on actual assignment

67

Global Variables

Variables can be declared outside functions Accessible from everywhere Initialized before main() started Live until program terminates Function static variables can be thought of as global

68

Potrebbero piacerti anche