Wed 10/8 2-mallocFree ------------ - malloc(#bytes) allocates memory on heap - ALWAYS used as (*)malloc(<#items>*sizeof()) - sizeof() is a "compile-time operator" - sizeof(), or - sizeof() - returns size of type the expression would evaluate to - doesn't evaluate the expression - see file 0.5-sizeofTest.c (developed during class) - see file 0-stringExample.c - we show two different ways of forming the result string in that code: 1. repeated concatenation -- slow, because you have to walk from the beginning of the result string each time you want to concatenate 2. using a temporary pointer that keeps track of where the next string to be concatenated should go - moving a pointer through memory is a common C idiom - so, having a pointer pointing into the middle of some data structure is reasonably common... - calloc(#items, sizeof(each item)) - returns zero'ed memory - calloc() makes it harder for programmer to make a mistake - can't forget to supply a count and a size or it won't compile - memory is zeroed - code using malloc may forget to correctly specify the size in bytes or to initialze the memory, and will compile just fine - see file 1-calloc.c - there are many ways to corrupt memory... - see file 2-memCorruption.c - it's often useful to a called routine to allocate the storage needed to hold its result, but... that means the calling code needs to free that storage - asprintf() is a (non-standard) version of sprintf() that allocates storage for its result - it's hard, or impossible, for caller to know how long the formatted string result will be, so allocating memory for result in caller isn't desirable - see file 3-calleeAllocates.c 3-pointVecDesign ---------------- Can you think like a Java programmer and write programs in C? -- Yes, sort of... - We looked at App.java, for about 20 seconds