Dynamic Memory Allocation - PowerPoint PPT Presentation

About This Presentation
Title:

Dynamic Memory Allocation

Description:

Dynamic Memory Allocation Problem: Don't know how much memory to allocate to an array Why? Memory is allocated to the correct size for a record to be written to disk – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 7
Provided by: set134
Learn more at: http://cs.sou.edu
Category:

less

Transcript and Presenter's Notes

Title: Dynamic Memory Allocation


1
Dynamic Memory Allocation
  • Problem Don't know how much memory to allocate
    to an array
  • Why?
  • Memory is allocated to the correct size for a
    record to be written to disk
  • Size depends upon a particular computer
    configuration
  • How? We use the C malloc and free functions

2
malloc() and free()
  • void malloc(size_t size)
  • void is a generic pointer for any type of data
  • size_t is a typedef for unsigned integers
  • allocates size in bytes
  • returns pointer to new memory or NULL
  • void free(void data)
  • releases memory pointed to by data
  • If data is NULL, no harm done
  • C has no garbage collection, skipping free
    results in memory leaks
  • Prevent dangling references set a pointer to
    NULL after free
  • Freeing from a function (pass a pointer to a
    pointer)
  • Function freeMyStructure( void data)
    free(data) data NULL)

Dangling reference a pointer to dynamic memory
that was released Alias Two pointers to the same
dynamically allocated memory
3
Rules
  • Never attempt to free memory twice
  • Never use a pointer after its memory was freed
    (dangling pointer)
  • Never attempt to free memory that wasn't
    allocated dynamically.
  • Set all pointers to null initially, and after
    freeing them

4
Example
  • Static allocation int nums100
  • Dynamic allocationint nums, nprintf("How
    Many?\n")scanf("d", n)nums malloc(n
    sizeof(int))free(nums)nums NULL

Note sizeof is an operator that finds the byte
length of a data type
5
Standard Programming Environment
  • Editors vi, emacs, pico
  • Compiler gcc or cc
  • Linker gcc or cc
  • Automated system builder make, ant
  • Profiler gprof (find inefficient functions)
  • Source control system SCCS, CVS
  • tracks code changes
  • coordinates changes among programmers
  • automatically assign release numbers

6
Hints for the last lab
  • The file syntax is modelyearrate\n
  • A sscanf s will read the entire string up to a
    space. If none, it reads everything
  • Find the pointer to the colon, and store a NULL
    ('\0')
  • How to find the colon? Either a character by
    character search, or by using the C strstr method
  • You can then use sscanf on the back portion

'\0'
Write a Comment
User Comments (0)
About PowerShow.com