Advertisement
cwchen

[C] Dangling pointer demo

Aug 27th, 2017
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main() {
  5.     const int SIZE = 10;
  6.  
  7.     // Allocate memory for the array a.
  8.     int* a = (int*) malloc(SIZE * sizeof(int));
  9.  
  10.     // Set the value in a
  11.     for (int i = 0; i < SIZE; i++) {
  12.         int j = i + 1;
  13.         a[i] = j * j;
  14.     }
  15.  
  16.     // Share the address of a to a1
  17.     int* a1 = a;
  18.  
  19.     // Oh, the memory of a is freed!
  20.     free(a);
  21.     a = NULL;
  22.  
  23.     /* Now a1 becomes dangling pointer.
  24.        Accessing data via a dangling pointer is
  25.        an undefined behavior. */
  26.     printf("%d\n", a1[3]);
  27.  
  28.     return 0;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement