AlexLeo

C How to Free a Pointer Example v2

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