Successfully reported this slideshow.

Introduction to pointers and memory management in C

14,553 views

Published on

Slides for a 30 minutes tutorial on pointers in C

Published in: Technology, Education

Introduction to pointers and memory management in C

  1. 1. Uri Dekel Carnegie Mellon University [email_address] Introduction to Pointers and Memory Management in C
  2. 2. Assumptions <ul><li>Audience familiar with: </li></ul><ul><ul><ul><li>Variables </li></ul></ul></ul><ul><ul><ul><li>Control structures </li></ul></ul></ul><ul><ul><ul><li>Function calls </li></ul></ul></ul><ul><ul><ul><li>Arrays and strings </li></ul></ul></ul><ul><li>Not familiar with </li></ul><ul><ul><li>Computer memory </li></ul></ul><ul><ul><li>Implementation of variables and function calls </li></ul></ul>Intro to Pointers and Memory in C
  3. 3. Topics <ul><li>Computer memory in general </li></ul><ul><li>Implementation of variables and function calls </li></ul><ul><li>Pointers and overcoming function limitations </li></ul><ul><li>Pointer arithmetic and arrays </li></ul><ul><li>Need and risks of dynamic memory allocation </li></ul>Intro to Pointers and Memory in C
  4. 4. Focus <ul><li>Understanding of concepts and techniques </li></ul><ul><li>Reasoning for use of specific techniques </li></ul><ul><li>Caveats to watch out for </li></ul>Intro to Pointers and Memory in C
  5. 5. Note on C versions <ul><li>Presented material is in C90 (old “Ansi C”) </li></ul><ul><ul><li>Supported by nearly all compilers </li></ul></ul><ul><ul><li>Basis for most legacy code </li></ul></ul><ul><li>Newer C’99 and later is different </li></ul><ul><ul><li>Allows some C++ conventions </li></ul></ul><ul><ul><li>Introduces new features </li></ul></ul><ul><ul><li>Not fully supported by all compilers </li></ul></ul>Intro to Pointers and Memory in C
  6. 6. Introduction to Computer Memory Intro to Pointers and Memory in C Background Dynamic Pointers
  7. 7. Why do we need memory? <ul><li>CPU operates on data in a handful of registers </li></ul><ul><li>Not enough for most applications </li></ul><ul><li>Memory is vast collection of “value holders” </li></ul><ul><li>Values copied to/from registers </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  8. 8. Memory needs to be organized <ul><li>Must be able to locate previously stored value </li></ul><ul><ul><li>Can’t rely on actual value </li></ul></ul><ul><li>Programmers see linear address space </li></ul><ul><li>Typical address space is vast </li></ul><ul><ul><li>32bit or 64bit </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  9. 9. What do we do with multi-byte values? <ul><li>Size of cell is limited </li></ul><ul><ul><li>Typically byte (8 bits, 0—255) </li></ul></ul><ul><li>Spread values in contiguous cells </li></ul><ul><ul><li>Only need to know starting address and size </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  10. 10. What do we do with multi-byte values? <ul><li>Breakup of large values must be consistent with their reassembly </li></ul><ul><ul><li>Where do we store the more-significant digits? </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  11. 11. Virtual Memory <ul><li>Modern OSs provide separate address space to processes </li></ul><ul><ul><li>Certain logical addresses mapped to physical addresses </li></ul></ul><ul><ul><li>Mechanism transparent </li></ul></ul><ul><ul><li>Overlapping addresses do not interfere </li></ul></ul><ul><ul><li>Not every address is mapped! </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  12. 12. Variables and Function Calls in C Background Dynamic Pointers Intro to Pointers and Memory in C
  13. 13. Variables <ul><li>A symbolic name for a specific memory location </li></ul><ul><ul><li>Can read and write contents </li></ul></ul><ul><ul><li>Guaranteed to exist every time it is used </li></ul></ul><ul><li>Type used to reassemble and interpret value </li></ul><ul><ul><li>How many cells? </li></ul></ul><ul><ul><li>How value is broken down </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  14. 14. Automatic variables <ul><li>Declared at a beginning of a block </li></ul><ul><li>Lifetime and scope correspond to block </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  15. 15. Allocating space for variables <ul><li>Variables are allocated space on stack </li></ul><ul><ul><li>Last-In-First-Out structure </li></ul></ul><ul><ul><li>Has a fixed base and grows “up” or “down” </li></ul></ul><ul><li>Newer variables allocated “above” earlier </li></ul><ul><li>Newer variables “die” before older </li></ul><ul><li>Stack resides in specific memory segment </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  16. 16. Program code and memory <ul><li>Our program (“code”) is stored in memory </li></ul><ul><ul><li>Dedicated “code segment” </li></ul></ul><ul><ul><li>Every instruction has an address </li></ul></ul><ul><ul><li>Every function has an address </li></ul></ul><ul><li>Most instructions are contiguous </li></ul><ul><li>CPU uses instruction pointer (IP) register for next address to execute </li></ul><ul><ul><li>Execution typically sequential </li></ul></ul><ul><ul><li>IP changes on branches </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  17. 17. Stack example (In function) Background Dynamic Pointers Intro to Pointers and Memory in C
  18. 18. Stack example (In function) Background Dynamic Pointers Intro to Pointers and Memory in C
  19. 19. What happens in function call? <ul><li>Copies of argument values pushed into stack </li></ul><ul><li>Return address pushed into stack </li></ul><ul><li>CPU IP aimed at beginning of function block </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  20. 20. What happens in function call? Background Dynamic Pointers Intro to Pointers and Memory in C
  21. 21. Returning from functions… <ul><li>All automatic variables of function are popped </li></ul><ul><li>Return address is popped </li></ul><ul><li>All passed arguments are popped </li></ul><ul><li>IP aimed at next instruction to execute in original function </li></ul><ul><li>Return value in register or stack </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  22. 22. Returning from functions… Background Dynamic Pointers Intro to Pointers and Memory in C
  23. 23. Attempting to write a swap function… Background Dynamic Pointers Intro to Pointers and Memory in C
  24. 24. Attempting to write a swap function… Background Dynamic Pointers Intro to Pointers and Memory in C
  25. 25. Attempting to write a swap function… Background Dynamic Pointers Intro to Pointers and Memory in C
  26. 26. Attempting to write a swap function… Background Dynamic Pointers Intro to Pointers and Memory in C
  27. 27. Pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  28. 28. Why pass-by-pointer? <ul><li>Functions always pass values by copying (pass-by-value) </li></ul><ul><li>They return a single value by copying </li></ul><ul><li>Changes to arguments in invoked functions have NO IMPACT on corresponding variables in invoking function </li></ul><ul><li>To change, we must “break through” to earlier stack locations. </li></ul><ul><li>Solution: </li></ul><ul><ul><li>1) Pass address of value holder represented by variable </li></ul></ul><ul><ul><li>2) Use that address to write directly into the value holder </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  29. 29. Pointers <ul><li>A pointer is a variable! </li></ul><ul><ul><li>It has an address and stores a value </li></ul></ul><ul><ul><li>But the value can be interpreted as an address </li></ul></ul><ul><li>X myX – declare variable of type X </li></ul><ul><li>X* pX – declare pointer to value of type X </li></ul><ul><ul><li>Pointer size depends on address space, not type! </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  30. 30. Assigning values to pointers <ul><li>Arbitrary numeric values </li></ul><ul><li>Address of variables </li></ul><ul><li>Values of other pointers </li></ul><ul><li>Address of functions (outside our scope) </li></ul><ul><li>Caveat: Avoid pointing at temporaries! </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  31. 31. Dereferencing pointers <ul><li>Accessing the pointed-to memory cell </li></ul><ul><ul><li>If pX is pointer, (*pX) is the value </li></ul></ul><ul><ul><li>Roughly, var is equivalent to (*(&var)) </li></ul></ul><ul><ul><li>Can serve as an lvalue! (can assign into it) </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  32. 32. Implementing Swap Background Dynamic Pointers Intro to Pointers and Memory in C
  33. 33. Implementing Swap Background Dynamic Pointers Intro to Pointers and Memory in C
  34. 34. Implementing Swap Background Dynamic Pointers Intro to Pointers and Memory in C
  35. 35. Implementing Swap Background Dynamic Pointers Intro to Pointers and Memory in C
  36. 36. Caveat – Uninitialized pointers <ul><li>Uninitialized pointers can contain junk </li></ul><ul><li>Dereferencing leads to random address </li></ul><ul><ul><li>Data overwrites, segmentation faults, etc. </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  37. 37. Caveat – NULL pointers <ul><li>Pointers to NULL should not be dereferenced </li></ul><ul><li>Equivalent to accessing address 0 </li></ul><ul><ul><li>Access may result in “Bus Error” on UNIX </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  38. 38. Caveats – Dangling references <ul><li>Avoid returning pointer to automatic vars </li></ul><ul><li>Don’t keep pointers to vars in inner blocks </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  39. 39. Casting pointers <ul><li>Converting between pointer types is risky </li></ul><ul><ul><li>Compiler will warn – Coercion possible </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  40. 40. Void* <ul><li>Pointer type used to represent addresses without any type information </li></ul><ul><li>Shouldn’t be dereferenced </li></ul><ul><li>Programmer responsible for coercion </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  41. 41. Const pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  42. 42. Pointers to pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  43. 43. Pointers to pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  44. 44. Pointers to pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  45. 45. Pointers to pointers Background Dynamic Pointers Intro to Pointers and Memory in C
  46. 46. Pointer Arithmetic <ul><li>C permits addition/subtraction on pointers </li></ul><ul><ul><li>Increments correspond to size of type value </li></ul></ul><ul><ul><li>Effective with contiguous set of variables </li></ul></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  47. 47. Pointers to array elements <ul><li>Pointers can aim at address of array elements </li></ul><ul><li>Refer to other elements with pointer arithmetic </li></ul>Background Dynamic Pointers Intro to Pointers and Memory in C
  48. 48. <ul><li>Array variable often treated as ptr to 1 st element </li></ul><ul><ul><li>Actually not a pointer </li></ul></ul><ul><ul><li>Computes into an rvalue for assignment to pointer </li></ul></ul><ul><ul><li>Passable to function that takes pointer or array </li></ul></ul><ul><ul><li>Not reassignable </li></ul></ul><ul><ul><li>Sizeof(ar) returns array size </li></ul></ul>The array “Variable” Background Dynamic Pointers Intro to Pointers and Memory in C
  49. 49. Dynamic Memory Allocation Background Dynamic Pointers Intro to Pointers and Memory in C
  50. 50. Why do we need to allocate memory? <ul><li>Size of data may not be known in advance </li></ul><ul><ul><li>May depend on user input </li></ul></ul><ul><ul><ul><li>e.g., Input N, then get N numbers, then present sorted </li></ul></ul></ul><ul><ul><li>May depend on result of calculation </li></ul></ul><ul><ul><li>Size may change over time </li></ul></ul><ul><ul><ul><li>e.g., Increase canvas size or number of pages </li></ul></ul></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  51. 51. Why do we need to allocate memory? <ul><li>Global and automatic arrays can only be declared with compile-time constant size </li></ul><ul><ul><li>(Relaxed in C99) </li></ul></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  52. 52. Why do we need to allocate memory? <ul><li>We want to control lifetime of data stored over time </li></ul><ul><ul><li>Live after function ends </li></ul></ul><ul><ul><li>Die before program terminates </li></ul></ul><ul><li>Basis for most data structures </li></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  53. 53. How do we allocate memory? <ul><li>void *malloc(size_t size); </li></ul><ul><ul><li>Submits request to allocate contiguous block of given size. </li></ul></ul><ul><ul><li>Size often specified as n*sizeof(type) </li></ul></ul><ul><ul><li>If failed, returns NULL </li></ul></ul><ul><ul><li>If valid, returns void pointer to new memory area </li></ul></ul><ul><ul><li>Programmer converts into pointer to first element </li></ul></ul><ul><ul><li>Pointer arithmetic or subscripts access rest of space </li></ul></ul><ul><ul><li>No bounds checking! </li></ul></ul><ul><ul><li>NULL otherwise </li></ul></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  54. 54. The heap <ul><li>A memory area provided to the process for allocating data </li></ul><ul><ul><li>Often limited </li></ul></ul><ul><li>Runtime tracks where all memory is allocated </li></ul><ul><li>Every allocation is contiguous </li></ul><ul><ul><li>Possibility of fragmentation even if enough total free space </li></ul></ul><ul><ul><li>No way to check in advance </li></ul></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  55. 55. Allocated memory must be freed! <ul><li>Programmer responsible for releasing dynamically allocated memory ASAP. </li></ul><ul><ul><li>Use free() operation </li></ul></ul><ul><ul><ul><li>void free(void *ptr); </li></ul></ul></ul><ul><ul><li>System will know how much space to clear </li></ul></ul><ul><li>Failure to free causes memory leak </li></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  56. 56. Malloc/Free example Intro to Pointers and Memory in C Background Dynamic Pointers
  57. 57. free() caveats <ul><li>Do not free a pointer prematurely </li></ul><ul><ul><li>Make sure it will not be accessed again via other pointer! </li></ul></ul><ul><ul><li>All other pointers are dangling references </li></ul></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  58. 58. free() caveats <ul><li>Once pointer to memory is lost, no way to free it </li></ul><ul><li>Do not release pointer to middle of allocated region </li></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  59. 59. free() caveats <ul><li>Freeing the same memory twice </li></ul><ul><li>Freeing an automatic variable </li></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  60. 60. Summary of covered topics <ul><li>Memory </li></ul><ul><ul><li>Address space necessary to understand pointers </li></ul></ul><ul><ul><li>Storage of large values </li></ul></ul><ul><li>Implementation of variables and calls </li></ul><ul><ul><li>Lifetime and effect on pointer validity </li></ul></ul><ul><ul><li>Need for pointers </li></ul></ul><ul><li>Pointers and their risks </li></ul><ul><li>Pointer arithmetic and relation to arrays </li></ul><ul><li>Need and risk of dynamic allocation </li></ul>Intro to Pointers and Memory in C Background Dynamic Pointers
  61. 61. Questions?
  62. 62. Backup materials Intro to Pointers and Memory in C
  63. 63. Topics not covered <ul><li>Pointers to pointers </li></ul><ul><li>Function pointers </li></ul><ul><li>Structs </li></ul><ul><li>Far pointers </li></ul>
  64. 64. Do not rely on stack organization!
  65. 65. Pointers can be compared
  66. 66. Caveats – Dangling references <ul><li>Do not keep pointers to dying variables </li></ul>
  67. 67. Null-terminated strings <ul><li>Strings: Array of chars terminated by ‘’ or 0. </li></ul><ul><li>String can take less space than actual array size </li></ul><ul><ul><li>Since can come early… </li></ul></ul><ul><li>Missing the will lead many functions past allocated memory </li></ul><ul><li>Storage depends on actual assignment </li></ul>
  68. 68. Global Variables <ul><li>Variables can be declared outside functions </li></ul><ul><li>Accessible from everywhere </li></ul><ul><li>Initialized before main() started </li></ul><ul><li>Live until program terminates </li></ul><ul><li>Function static variables can be thought of as global </li></ul>

×