CS 240 Programming in C Pointers September 28, 2019 Haoyu Wang UMass Boston CS 240 September 28, 2019 1 / 10
Runtime Memory Layout Text segment: machine 0xFFFF instructions of program stack Data segment: constants, global variables (static or not) and local static variables Heap: dynamically allocated space, malloc() Stack: runtime call stack Actual parameters heap (malloc’d data) (arguments) for functions data (global variables) Local (automatic) variables Return address text (program code) 0x0000 Returned value Haoyu Wang UMass Boston CS 240 September 28, 2019 2 / 10
Data Segment See demo. Haoyu Wang UMass Boston CS 240 September 28, 2019 3 / 10
Stack frame C program’s stack segment is consisted of nested function frames or stack frames. the main frame is the most outside frame, and the starting point of the program. Each function call will start one new frame in the stack, and after exit of function, its stack frame gets destroyed with every thing in it. Stack frames works like stack structure, the first created frame gets destroyed at last, which is the main, and the last created stack frame gets destroyed first. FILO. Stack frame growing from high address to low address. Haoyu Wang UMass Boston CS 240 September 28, 2019 4 / 10
Local variable See demo. Haoyu Wang UMass Boston CS 240 September 28, 2019 5 / 10
Pointer a multi-dimensional array See demo. Are "array" and "&array" the same thing? See demo. Haoyu Wang UMass Boston CS 240 September 28, 2019 6 / 10
Pointer to arrays See demo. Haoyu Wang UMass Boston CS 240 September 28, 2019 7 / 10
malloc and free The functions malloc and calloc obtain blocks of memory dynamically. void *malloc(size_t n) returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied. void *calloc(size_t n, size_t size) returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. free(p) frees the space pointed to by p , where p was originally obtained by a call to malloc or calloc . Haoyu Wang UMass Boston CS 240 September 28, 2019 8 / 10
Pointer to function In C, a function itself is not a variable, but it is possible to define pointers to functions, which can be assigned, placed in arrays, passed to functions, returned by functions, and so on. Haoyu Wang UMass Boston CS 240 September 28, 2019 9 / 10
Complicated Declarations See demo. Haoyu Wang UMass Boston CS 240 September 28, 2019 10 / 10
Recommend
More recommend