Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Memory Allocation

Similar presentations


Presentation on theme: "Dynamic Memory Allocation"— 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 free(void * data)
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 nums[100;
Dynamic allocation int *nums, n; printf("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: 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' F o r d : 9 8 . 5


Download ppt "Dynamic Memory Allocation"

Similar presentations


Ads by Google