AlexLeo

C How to Free a Pointer Example v3

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