Top Banner
[email protected] Crash Course in C Dynamic Allocation
32

Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Jun 21, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

[email protected]

Cra

sh C

ours

e in

C

Dyn

amic

Allo

cati

on

Page 2: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 3: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

malloc

The

mal

loc

func

tion

is u

sed

to a

lloca

te m

emor

y

void *malloc(size_t sz);

sz

Thi

s ar

gum

ent s

peci

fies

the

size

, in

byte

s, o

f

The

fun

ctio

n re

turn

s an

unt

yped

poi

nter

to th

e

the

mem

ory

to b

e al

loca

ted.

allo

cate

d m

emor

y, o

r N

UL

L if

the

mem

ory

cann

otbe

allo

cate

d.

Page 4: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

int main(void)

{ return 0;

} printf("|double| = %d\n",

sizeof(double));

printf("|double| = %d\n", 8);

|double| = 8

Dyn

amic

Allo

catio

n of

Mem

ory

sizeof

Alw

ays

use

size

of to

det

erm

ine

the

size

of

data

.

At c

ompi

le ti

me,

a s

izeo

f ex

pres

sion

is e

xpan

ded

into

an

inte

ger.

Page 5: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 6: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 7: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

{ char name[64];

strcpy(name, "Nicholas Ingolia");

return name;

}char *get_name(void)

Dyn

amic

Allo

catio

n of

Mem

ory

Pers

iste

nce

of A

lloca

ted

Mem

ory

The

sto

rage

ass

ocia

ted

with

nam

e di

sapp

ears

whe

n

Thu

s, th

e re

turn

ed p

oint

er is

use

less

and

dan

gero

us.

the

func

tion

retu

rns.

Page 8: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Pers

iste

nce

of A

lloca

ted

Mem

ory

{ static char val[256];

int idx = keyidx(key);

strcpy(val, keyvals[idx].val);

return val;

}char *lookup(char *key)

Thi

s is

an

acce

ptab

le s

olut

ion.

..

Exc

ept,

the

next

cal

l to

look

up o

verw

rite

s th

e ol

d va

l, w

hich

is a

pro

blem

.

Page 9: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Pers

iste

nce

of A

lloca

ted

Mem

ory

char *lookup(char *key)

{ char *val;

int idx = keyidx(key);

val = malloc(sizeof(char)

* (strlen(vals[idx]) + 1);

strcpy(val, vals[idx]);

return val;

} Val

will

per

sist

unt

il ex

plic

itly

deal

loca

ted.

A n

ew v

al w

ill b

e cr

eate

d on

eve

ry c

all t

o lo

okup

.

Page 10: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Allo

catin

g St

ring

s

char *strdup(const char *str)

{ char *newstr;

int len = strlen(str);

newstr = malloc(sizeof(char)

* (len + 1));

strcpy(newstr, str);

return newstr;

} Stri

ngs

need

an

extr

a ch

ar to

hol

d th

e 0

term

inat

or.

Page 11: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 12: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Allo

catin

g A

rray

s

double *normalize(double *d, int nd)

{ int i;

for (i = 0; i < nd; i++)

...

{

double *normalize(double *d, int nd)

{ double dnorm[nd];

double *dnorm;

dnorm = malloc(sizeof(double)*nd);

...

Page 13: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 14: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 15: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Pers

iste

nce

of A

lloca

ted

Mem

ory

Allo

cate

d m

emor

y pe

rsis

ts

Thu

s, it

is n

eces

sary

to r

elea

se u

nnee

ded

mem

ory

Failu

re to

rel

ease

una

lloca

ted

mem

ory

caus

es th

e

Free

all

"tem

pora

ry"

allo

cate

d m

emor

y; e

nsur

e th

at

Not

e w

hich

fun

ctio

ns r

etur

n po

inte

rs to

new

mem

ory

Free

allo

cate

d m

emor

y "i

nsid

e" d

ata

stru

ctur

es

prog

ram

to c

onsu

me

syst

em r

esou

rces

.

mem

ory

is f

reed

bef

ore

all p

ossi

ble

retu

rns.

Page 16: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Rel

easi

ng A

lloca

ted

Mem

ory

The

fre

e fu

nctio

n re

leas

es a

lloca

ted

mem

ory

void free(void *p)

pA

poi

nter

to a

lloca

ted

mem

ory

It is

ver

y im

port

ant t

hat f

ree

only

be

calle

d on

apo

inte

r re

turn

ed b

y m

allo

c or

str

dup.

Free

may

be

calle

d on

ly o

nce

on s

uch

a po

inte

r.

Nei

ther

the

poin

ter

nor

any

othe

r de

rive

d fr

om it

m

ay b

e us

ed a

fter

it is

fre

ed.

Page 17: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Rel

easi

ng A

lloca

ted

Mem

ory

void foo(const char *str)

{ char *buf;

buf = strdup(str);

munge(buf);

display(buf);

free(buf);

}

Page 18: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 19: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

rho[17][37] = 0.666;

rho

...

3.2

8.1

5.7

0.2

0.7

3.4

8.2

5.5

0.1

0.3

3.4

8.2

5.5

0.1

0.3

3.2

8.1

5.7

0.2

0.7

A m

ultid

imen

sion

al a

rray

in C

is a

n ar

ray

of a

rray

s.

Mul

tidim

ensi

onal

Arr

ays

...

...

...

...

double rho[NROWS][NCOLS];

Page 20: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

al A

lloca

tion

of M

emor

y

double *new_2d(int lx, int ly)

{ double **dx;

int x;

dx = malloc(sizeof(double *)*lx);

for (x = 0; x < lx; x++) {

dx[x] = malloc(sizeof(double)

* ly);

}

return dx;

}

Mul

tidim

ensi

onal

Arr

ays

Page 21: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Rel

easi

ng M

ultid

imen

sion

al A

rray

s

void free_2d(double **d,

int nx, int ny)

{ int x;

for (x = 0; x < nx; x++) {

free(d[x]);

}

free(d);

} All

allo

cate

d m

emor

y m

ust b

e fr

eed.

Page 22: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Dyn

amic

Allo

catio

n of

Mem

ory

Alte

rnat

e M

ultid

imen

sion

al A

rray

s

Rat

her

than

usi

ng a

n ar

ray

of a

rray

s, it

is p

ossi

ble

rho[

double rho[NROWS * NCOLS];

(17 * NCOLS) + 37] = 0.666;

For

100

row

s, 5

0 co

lum

s:

but t

he a

ctua

l ind

ex m

ust b

e co

mpu

ted.

Thi

s re

quir

es o

nly

a si

ngle

blo

ck o

f m

emor

y,

...

...

...

...

0,49

1,1

1,0

1,49

99,099,1

99,49

0,1

0,0

to u

se a

sin

gle

arra

y of

siz

e (xy)

Page 23: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CA

dvan

tage

s of

Mod

ular

Pro

gram

min

g

Prog

ram

s ou

ght t

o be

div

ided

into

sm

alle

r m

odul

es

Mod

ules

pro

vide

con

cept

ual b

ound

arie

s

Indi

vidu

al m

odul

es c

an b

e te

sted

, deb

ugge

d, a

nd r

euse

d

Mod

ules

ass

ist i

n al

loca

tion

man

agem

ent

Page 24: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CIn

terf

aces

and

Im

plem

enta

tions

A C

pro

gram

can

be

brok

en in

to m

ultip

le s

ourc

e fi

les

Usi

ng o

ne s

ourc

e fi

le p

er m

odul

e he

lps

enfo

rce

mod

ule

boun

dari

es

Hea

der

file

s sp

ecif

y th

e in

terf

ace

to a

mod

ule

Inte

rfac

es in

clud

e fu

nctio

n an

d da

ta ty

pe d

ecla

ratio

ns

Sour

ce f

iles

prov

ide

the

impl

emen

tatio

n of

a m

odul

eIm

plem

enta

tions

pro

vide

def

initi

ons

of f

unct

ions

prom

ised

by

the

mod

ule

in th

e in

terf

ace.

Page 25: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CH

eade

r Fi

les

/* llist.h */

#if !defined(_llist_h)

struct llist_struct;

typedef struct llist_struct llist;

llist *llist_new(void);

void llist_free(llist *);

llist *llist_insert(llist *,

const char *);

llist *llist_remove(llist *,

const char *);

int llist_contains(const llist *,

const char *);

#endif

#define _llist_h 1

Page 26: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CH

eade

rs

The

C p

roce

ssor

can

be

used

to p

rote

ct a

gain

st

mul

tiple

incl

usio

ns o

f a

head

er f

ile

#if !defined(_header_h)

#define _header_h 1

...

#endif

Page 27: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Priv

ate

Stru

ctur

e D

efin

ition

s

struct llist_struct;

typedef struct llist_struct llist;

llist.c

llist.h

struct llist_struct {

llist *next;

};

Poin

ters

to a

n lli

st c

an b

e us

ed a

nyw

here

.

The

fie

lds

of a

n lli

st c

an b

e ac

cess

ed o

nly

in w

ithin

th

e lli

st.c

sou

rce

file

impl

emen

ting

an ll

ist.

char *elt;

Mod

ular

Pro

gram

min

g in

C

Page 28: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CIm

mut

abili

ty

prom

ise

not t

o ch

ange

the

argu

men

t.A

con

stan

t poi

nter

in a

fun

ctio

n de

clar

atio

n is

a

char *strdup(const char *str);

The

cal

ling

func

tion

know

s th

at th

e st

r pa

ssed

to

strd

up w

ill n

ot b

e ch

ange

d.

C e

nfor

ces

this

agr

eem

ent,

thou

gh it

can

be

over

ridd

en

str[0] = ’a’;

Page 29: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is
Page 30: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

Mod

ular

Pro

gram

min

g in

CC

ompi

ling

and

Lin

king

A c

ompi

led

obje

ct is

a c

olle

ctio

n of

fun

ctio

ns a

wai

ting

com

plet

ion

by li

nkin

g

llist_new

...

malloc

...

strdup

...

llist_free

... ...

free

Page 31: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is

llist_new 2718281

strdup 3141592

malloc 1618034

Mod

ular

Pro

gram

min

g in

CC

ompi

latio

n an

d L

inki

ng

Lin

king

ass

embl

es o

bjec

ts in

to a

pro

gram

The

link

er b

uild

s a

tabl

e of

fun

ctio

ns a

nd g

loba

l va

riab

les

prov

ided

by

vari

ous

obje

cts

The

tabl

e is

use

d to

"co

mpl

ete"

the

obje

cts

blllist_new

bl 2718281

...

...

Page 32: Crash Course in C Dynamic Allocationweb.mit.edu/ingolia/CCC01/dynalloc.pdfDynamic Allocation of Memory Alternate Multidimensional Arrays Rather than using an array of arrays, it is