90 likes | 245 Views
Weeks 7-8. Memory allocation Pointers functions Complex structures with pointers, structures, etc Dynamic structures. Memory Allocation. Where we have dealt with memory issues: Address arithmetic: we had to use array to get memory
E N D
Weeks 7-8 • Memory allocation • Pointers functions • Complex structures with pointers, structures, etc • Dynamic structures
Memory Allocation • Where we have dealt with memory issues: • Address arithmetic: we had to use array to get memory • Return characters strings: It is incorrect to return a local char array. char [] encode(int x) { char temp[4]; temp[0]=‘A’ + x; return temp; /* wrong */ } buff[256] cp malloc(256)
Memory Interface • Interfaces: from <stdlib.h> • malloc: void *malloc(int size); • calloc: void *calloc(int num, int size); • realloc: void *realloc(void *ptr, int size); • free: void free(void *ptr); • Miscellaneous • memset: void *memset(void *ptr, int c, int size); • bzero: void bzero(void *ptr, int size);
Usages • To get a dynamic memory area, which exists until free • To avoid a really large array • To avoid static arrays (array with fixed sizes) • malloc/free: int main() { int i; struct student s; scanf(“%d %d”, &s.id, &s.num); s.bookids = (int *)malloc(sizeof(int)*num); while (i=0; i< s.num; i++){ scanf(“%d”, &s.bookids[i]); } free(s.bookids); return 0; } struct student { int id; int num; /* wrong */ int bookids[num]; int *bookids; };
Memory issues • Memory Leak • Pointer aliases • Dangling pointers • Garbage collection
Rules • Do NOT dereference a pointer before its assigned a memory area • Dereference only pointers with type than void* • Always free the memory you allocated • Be cautious of your pointer aliases and dangling pointers. • Initialize your pointers with NULL and do sanity checks.
Pointer functions • Syntax: • type (* name) (argument list); • Compare function prototypes: • type name (argument list); • Usage for ( i=0; i<20; i++) max = max > a[i] ? max: a[i]; return max; } int main() { int job, result, score[20]; int (*func)(int []); scanf(“%d”, &job); func = job == 1 ? find_average : find_max; result = func(score); return 0; } int find_average(int a[]) { int i, sum; for ( i=0; i<20; i++) sum +=a[i]; return sum/20; } int find_max(int a[]) { int max=a[0];
Passing Function pointers int main() { int job, result, score[20]; scanf(“%d”, &job); result = process (job, score, find_average, find_max); return 0; } int process(int job, int score[], int (*)a(int []), int(*)b(int [])); { int (*func)(int []); func = job ==1? a:b; return func(score); }
Pointer functions in Structures struct course { int course_num; int scores[20]; int (*find_min)(int []); int (*average)(int []); }; int main() { int result; struct course c459; … result=c459.find_min(c459.scores); … result=c459.average(c459.scores); … return 0; }