60 likes | 147 Views
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().
E N D
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() • 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
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
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
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
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'