AlexLeo

C How to Free a Pointer Example

Mar 5th, 2015
337
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void freePointer(int** pointer);
  5.  
  6. int main()
  7. {
  8.     int* pointer = (int*)malloc(sizeof(int));
  9.     *pointer = 10;
  10.  
  11.     printf("pointer 的數值 = %p\n", pointer);
  12.     printf("對 pointer 取值 = %d\n", *pointer);
  13.     printf("====== 釋放 pointer ======\n");
  14.     /*
  15.     free(pointer);
  16.     printf("pointer 的數值 = %p\n", pointer);
  17.     printf("對 pointer 取值 = %d\n", *pointer);
  18.     printf("===== pointer 為 NULL ====\n");
  19.     pointer = NULL;
  20.     printf("pointer 的數值 = %p\n", pointer);
  21.     printf("對 pointer 取值 = %d\n", *pointer);
  22.     */
  23.     freePointer(&pointer);
  24.     printf("pointer 的數值 = %p\n", pointer);
  25.     printf("對 pointer 取值 = %d\n", *pointer);
  26.  
  27.     return 0;
  28. }
  29.  
  30.  
  31. void freePointer(int** pointer)
  32. {
  33.     free(*pointer);
  34.     *pointer = NULL;
  35. }
  36.  
  37. /***************************** 執行結果 ******************************
  38. pointer 的數值 = 00872F88
  39. 對 pointer 取值 = 10
  40. ====== 釋放 pointer ======
  41. pointer 的數值 = 00000000
  42.  
  43. Process returned -1073741819 (0xC0000005)   execution time : 4.984 s
  44. Press any key to continue.
  45. *********************************************************************/
RAW Paste Data