Title: Weeks 7-8
1Weeks 7-8
- Memory allocation
- Pointers functions
- Complex structures with pointers, structures, etc
- Dynamic structures
2Memory 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 temp4
temp0A x return temp / wrong /
buff256
cp
malloc(256)
3Memory Interface
- Interfaces from ltstdlib.hgt
- 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)
4Usages
- 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 (i0
ilt s.num i) scanf(d,
s.bookidsi) free(s.bookids)
return 0
struct student int id int num /
wrong / int bookidsnum int
bookids
5Memory issues
- Memory Leak
- Pointer aliases
- Dangling pointers
- Garbage collection
6Rules
- 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.
7Pointer functions
- Syntax
- type ( name) (argument list)
- Compare function prototypes
- type name (argument list)
- Usage
for ( i0 ilt20 i) max max gt ai
? max ai return max int main()
int job, result, score20 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
( i0 ilt20 i) sum ai return
sum/20 int find_max(int a) int
maxa0
8Passing Function pointers
int main() int job, result, score20
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? ab return
func(score)
9Pointer functions in Structures
struct course int course_num int
scores20 int (find_min)(int ) int
(average)(int )
int main() int result struct course
c459 resultc459.find_min(c459.scores)
resultc459.average(c459.scores)
return 0