Dynamic Allocation - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Dynamic Allocation

Description:

However, for real world programs memory leaks are not acceptable. ... char *cp = malloc(1); Which is more likely. Program will ... realloc(cp, 0) free(cp) ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 44
Provided by: BillL161
Category:
Tags: allocation | cp | dynamic | real

less

Transcript and Presenter's Notes

Title: Dynamic Allocation


1
Dynamic Allocation
2
Outline
  • Dynamic Memory Allocation
  • Dynamically Sized Arrays

3
Dynamic Allocation
  • Used when space requirements are unknown at
    compile time.
  • Most of the time the amount of space required is
    unknown at compile time.
  • Example
  • Need space to allow user to enter some data
  • 80 bytes? 132? 1? 256? 255?
  • Three Friends
  • malloc
  • realloc
  • free

4
malloc
  • int ip
  • ip malloc(10 sizeof(int))
  • if(ip NULL)
  • / Handle Error! /
  • Options for handling error
  • Abort
  • Ask again
  • Save user data
  • Ask for less
  • Free up something

5
malloc
  • int ip
  • ip malloc(10 sizeof(int))
  • if(ip NULL)
  • / Handle Error! /
  • Note how incredibly bad it would be to use the
    assignment operator!
  • The pointer would be set to NULL
  • The error code would be skipped
  • Some programmers use NULL ip

6
malloc -- What happens?
  • int foo(int n)
  • int ip
  • ip malloc(n sizeof(int))
  • if(ip NULL)
  • / Handle Error! /
  • ...

Stack
Heap
40 bytes
Data
Code
7
Anticipating Problems
  • ip malloc(10 sizeof(int))
  • if(ip NULL)
  • What might go wrong?
  • Be paranoid!

8
Welcome to my nightmare!
  • ip malloc(10 sizeof(int))
  • Code foolishly inserted here!
  • if(ip NULL)
  • Be afraid.
  • Be very afraid!

9
Tricky but safe
  • if((ip malloc(10sizeof(int))) NULL)
  • / Handle Error Here /

10
Using the space
  • int sample(int n)
  • int i
  • int ip
  • if((ip malloc(nsizeof(int))) NULL)
  • / Handle Error Here /
  • for(i 0 i lt n i)
  • ipi 0
  • ...

11
Flexibility
  • define MAX 10
  • int ip
  • ip malloc(MAX sizeof(int))
  • What if we change the type of int ip???
  • define MAX 10
  • int ip
  • ip malloc(MAX sizeof(ip))

12
After some calls to malloc
Stack
Heap
Non-constant data
Constant data
Code
13
What does runtime track?
  • Address
  • 1400
  • 2400
  • 3000
  • 4000
  • Size
  • 200
  • 300
  • 100
  • 500

Notice that no record is made of the name of any
pointer
14
What happens?
  • int ip
  • ip malloc(...)
  • .
  • .
  • .
  • free(ip)

15
Prototypes
  • void malloc(size_t n)
  • void free(void p)
  • void realloc(void p, size_t n)
  • What is this mysterious void pointer?

16
void pointer
  • Not originally in c
  • Relatively recent addition
  • Basically a generic pointer
  • Intended for use in applications like free where
    the block of memory located at some address will
    be freed without any necessity of defining the
    type

17
Powerful Dangerous
  • void vp
  • char cp
  • int ip
  • ip cp / illegal /
  • Instead
  • ip (int )cp
  • Or
  • vp cp / Legal, powerful and /
  • ip vp / dangerous!!! /
  • Why is this being done?

18
Casting
  • Usually casting is not required
  • May be masking a problem
  • int ip
  • char cp
  • ...
  • cp x
  • ip ???
  • ip 42
  • cp ???

19
Warnings
  • Using void pointers as a crutch to get around
    casting is a bad thing!
  • Malloc doesnt care what you are doing with a
    block of memory it allocates to you. What you do
    with the memory is your responsibility
  • Passing in random values to free is a bad thing!
  • Free does not change contents of block that was
    freed
  • Free does not change pointer
  • After a call to free it is possible to do
    anything to the freed memory that was possible
    before the call!!!
  • Definitely a bad thing!!!

20
Persistent Data I
  • char foo(void)
  • static char ca10
  • return ca
  • Anyone calling this function now has access to
    this block. Could be dangerous. Why?
  • Note that this approach is not dynamic

21
Example
  • char strFromUnsigned(unsigned u)
  • static char strDigits ?????
  • char pch
  • pch strDigits5
  • do
  • --pch (u 10) '0'
  • while((u / 10) gt 0)
  • return pch

22
Problem in use
  • strHighScore strFromUnsigned(HighScore)
  • .
  • .
  • .
  • strThisScore strFromUnsigned(ThisScore)

23
Persistent Data II
  • char foo(void)
  • char ca10
  • return ca
  • Since ca was allocated on stack during function
    call pointer returned is now pointing to who
    knows what
  • Bad

24
Persistent Data III
  • char foo(void)
  • char ca malloc(...)
  • / error checking but no free /
  • return ca

25
Memory Leaks
  • Memory leaks occur when the programmer loses
    track of memory allocated by malloc or other
    functions that call malloc
  • void foo(void)
  • char ca malloc(...)
  • / no free /
  • return
  • Bad

26
Memory Leaks
  • Obviously a program that runs for a fraction of a
    second and then terminates will not cause a
    problem if it leaks a few bytes of memory.
  • However, for real world programs memory leaks are
    not acceptable.
  • For the educational purposes of this class your
    programs will be required to leak no memory!
  • Programs submitted with memory leaks may incur
    severe penalties.

27
Memory Management
  • Some functions that call malloc
  • calloc
  • strdup
  • regcmp
  • others...
  • C doesnt do automatic memory management for
    efficiency reasons
  • If you want to manage memory...do it yourself!

28
Memory Management
  • Ok?
  • int ip, ip2
  • ip malloc(...)
  • ip2 ip
  • free(ip)
  • ip2 42
  • Yes
  • No
  • Maybe

29
More...
  • int ip, ip2 / Line 1 /
  • ip malloc(...) / Line 2 /
  • / Error checking here /
  • ip2 ip / Line 3 /
  • ip 4 / Line 4 /
  • free(ip) / Line 5 /
  • free(ip2) / Line 6 /
  • Problem line?

30
Realloc
  • ptr realloc(ptr, num_bytes)
  • What it does (conceptually)
  • Find space for new allocation
  • Copy original data into new space
  • Free old space
  • Return pointer to new space

31
Realloc
ptr
in-use
Before
in-use
After
32
Realloc What might happen
Before
ptr
unused
After
33
Dynamic Allocation
  • int ip malloc(...)
  • malloc may allocate more space than requested
  • Why?
  • Efficiency
  • Typically if you ask for 1 byte you will get 8.
  • Given this line of code
  • char cp malloc(1)
  • Which is more likely
  • Program will probably keep this memory as is
  • Program will eventually realloc
  • How much can you safely use?

34
Safety
  • Program should only use memory actually requested
  • Big problem! Why?
  • Program that oversteps bounds may work...
  • Sometimes!
  • Note...
  • char cp malloc(1)
  • ADDR SIZE
  • cp 8 (maybe!)
  • Now...
  • realloc(cp,6)
  • will return same pointer thus...

35
Realloc
  • May return same pointer passed to it without
    indicating any problem.
  • Using memory beyond that which has been allocated
    may work
  • Some of the time
  • Normally it will work when tested by a student
    but will fail when tested by a TA (for a grade)
  • Go figure
  • Thus the No Mercy rule

36
Realloc
  • Realloc may return
  • same pointer
  • different pointer
  • NULL
  • Is this a good idea?
  • cp realloc(cp, n)
  • Yes
  • No
  • Sometimes

37
Realloc
  • Is this a good idea?
  • cp realloc(cp, n)
  • No!
  • If realloc returns NULL cp is lost
  • Memory Leak!

38
How to do it
  • void tmp
  • if((tmp realloc(cp,...)) NULL)
  • / realloc error /
  • else
  • cp tmp
  • free(tmp)

NO!
39
Additional Information
  • realloc(NULL, n) ? malloc(n)
  • realloc(cp, 0) ? free(cp)
  • These can be used to make realloc work in a
    single loop design to build a dynamic structure
    such as a linked list.

40
Example
  • int size 0 / Size of "array" /
  • int ip NULL / Pointer to "array" /
  • int temp
  • int i
  • char buffer80
  • while(fgets(buffer, 80, stdin) ! NULL)
  • bufferstrlen(buffer) - 1 '\0'
  • size
  • if( (temp realloc(ip,
    sizesizeof(temp))) NULL)
  • fprintf(stderr, "Realloc failure\n")
  • exit(EXIT_FAILURE)
  • ip temp
  • ipsize - 1 strtol(buffer, NULL, 10)

41
Dynamic AllocationWhat can go wrong?
  • Allocate a block of memory and use the contents
    without initialization
  • Free a block but continue to use the contents
  • Call realloc to expand a block of memory and then
    once moved continue to use the old address
  • Allocate a block and lose it by losing the value
    of the pointer
  • Read or write beyond the boundries of the block
  • FAIL TO NOTICE ERROR CONDITIONS

42
Questions?
43
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com