Docsity

Memory Allocation: Understanding Dynamic and Static Memory Allocation in C - Prof. Scott R, Study notes of Computer Science

Partial preview of the text

Download Memory Allocation: Understanding Dynamic and Static Memory Allocation in C - Prof. Scott R and more Study notes Computer Science in PDF only on Docsity!

Memory Allocation

Scott Rixner

[email protected]

Scott Rixner

Memory Allocation

Big Picture C gives you access to underlying data

representations & layout

Š^

Needed for systems programming

Š^

Inconvenient for application programming

Š^

Necessary to understand

Memory is a finite sequence of fixed-size

storage cells

Š^

Most machines view storage cells as bytes^ •

“byte-addresses” • Individual bits are not addressable

Š^

May also view storage cells as words

Scott Rixner

Memory Allocation

Allocation For all data, memory must be

allocated

Š^

Allocated = memory space reserved

Two questions:

Š^

When do we know the size to allocate?

Š^

When do we allocate?

Two possible answers for each:

Š^

Compile-time (

static

)

Š^

Run-time (

dynamic

)

Scott Rixner

Memory Allocation

How much memory to allocate? Sometimes obvious: Sometimes not:

Š^

How will these be used???^ •

Will they point to already allocated memory (what we’veseen so far)?

-^

Will new memory need to be allocated (we haven’t seen thisyet)?

char

c;

int

array[10];

One byte^ 10 * sizeof(int) (= 40, usually)

char

*c; int

*array;

Is this going to point to onecharacter or a string?^ How big will this array be?

Scott Rixner

Memory Allocation

Using malloc() i

and

array

are interchangeable

Š^

Arrays

≈

pointers to the initial (0th) array element

Š^

i^

could point to an array, as well

Š^

May change over the course of the program

Allocated memory is

not

initialized!

Š^

calloc

zeros allocated memory (otherwise, same

as

malloc

)

int *i;int *array;i = (int *) malloc(sizeof(int));array = (int ) malloc(num_items * sizeof(int));i = 3;array[3] = 5;

Statically allocatesspace for 2 pointers

Dynamicallyallocates space for data

Scott Rixner

Memory Allocation

Using malloc() Always check the return value of system calls

like

malloc()

for errors

Š^

For brevity, won’t in class

Š^

Textbook uses capitalization convention^ •

Capitalized version of functions are wrappers thatcheck for errors and exit if they occur (i.e.

Malloc

-^

May not be appropriate to always exit on a

malloc

error, though, as you may be able to recover memory

int

a^

=^

(int

malloc(num_items

  • sizeof(int));

if

(a

NULL)

fprintf(stderr,“Out

of

memory.\n”);

exit(1); }

Scott Rixner

Memory Allocation

When to Allocate? Static time

Š^

Some local variables:

int

f(…) {

static

int

value;

} int

main() {

Confusingly, local static

has nothing to

do with global

static

One copy exists forall calls – allocatedat compile-time

Scott Rixner

Memory Allocation

Allocation in Process Memory

User Stack

Shared Libraries

Heap

Read/Write Data

Read-only Code and Data

Unused

0xFFFFFFFF 0x

Static size, dynamic allocation Dynamic size, dynamic allocation Static size, static allocation

Global variables

(and static local variables)

Local variables

Programmer controlled (variable-sized objects)

0xFFBEC000 0xFF3DC000 0x

Scott Rixner

Memory Allocation

Deallocation malloc()

allocates memory explicitly

Š^

Must also deallocate it explicitly (using

free()

)!

Š^

Not automatically deallocated (garbage collected)as in Scheme & Java

Š^

Forgetting to deallocate leads to memory leaks &running out of memory

Must not use a freed pointer unless reassigned

or reallocated

int

*a

(int *)

malloc(num_items

sizeof(int));

… free(a);… a^

=^

(int

malloc(

num_items

sizeof(int));

Scott Rixner

Memory Allocation

Deallocation Space allocated by malloc() is freed when the

program terminates

Š^

If data structure is used until program termination,don’t need to free

Š^

Entire process’ memory is deallocated

Assumes virtual memory implementation is

bug-free!

Š^

Bad assumption

Scott Rixner

Memory Allocation

Pitfall^ void^ foo()^ {

Date

*today; today

create_date3(9,

use

“today”

... return; }

Memory is still allocated for “today”!Will never be deallocated (callingfunction doesn’t even know about it)

Potential problem: memoryallocation is performed inthis function (may notknow its implementation)

Scott Rixner

Memory Allocation

Possible Solutions^ voidfoo(){

Date

*today; today

create_date3(…);

use

“today”

... free(today);return; }

voidfoo(){

Date

*today; today

create_date3(…);

use

“today”

... destroy_date(today);return; }

Explicitly deallocate memory –specification of create_date3must tell you to do this

Complete the abstraction – “create”has a corresponding “destroy”

Scott Rixner

Memory Allocation

What’s Wrong With This Code? Consider

*j = f()

Leads to referencing deallocated memory

Š^

Never return a pointer to a local variable!

Behavior depends on allocation pattern

Š^

Space not reallocated (unlikely)

works

Š^

Space reallocated

very unpredictable

int

*make_array(…) {

int

array[10];

… return

array;

int

*f(…) {

int

i;

… return

&i;

Scott Rixner

Memory Allocation

One Solution Allocate with malloc(), and return its pointer

Š^

Upon return, space for local pointer variable isdeallocated

Š^

But the

malloc

-ed space isn’t deallocated until it is

free

-d

Š^

Potential memory leak if caller is not careful, aswith create_date3…

int *f(…) {

int *i_ptr =

(int *) malloc(sizeof(int)); … return i_ptr; }

int *make_array(…) {

int *array =

(int *) malloc(10 * sizeof(int)); … return array; }