1 / 6

Dynamic Memory Allocation

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. malloc() and free().

kim-spears
Download Presentation

Dynamic Memory Allocation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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, so skipping free can result in serious memory leaks

  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. Static allocation: int nums[100; Dynamic allocationint *nums, n;printf("How Many?\n");scanf("%d", &n);nums = malloc(n * sizeof(int));•••free(nums);nums = NULL; Example 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. F o r d : 9 8 : 9 . 5 0 Hints for the last lab • The file syntax is: model:year:rate\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'

More Related