Thread: Accessing a pointer after it has been freed

  1. #16
    Registered User
    Join Date
    Jun 2004
    Posts
    201
    I asked on comp.lang.c and this is a good example when your program could crash on using a freed pointer. its a non existing platform but its still UB


    Consider a platform that has separate data and address registers. Also
    consider that this platform has virtual memory, and that free() unmaps
    the passed-in pointer from the address space. The mere act of loading
    the p1 pointer into a register in order to compare it to another
    platform could cause a bus error, crash the program, etc.

  2. #17
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by CornedBee
    Not in the way you expected, but look at 6.5.8.5, which defines the semantics of relational operations on pointers.
    Ta, CornedBee. It made sense to me that comparing a free'd pointer with something wouldn't be defined. I read that section, but my mind must have drifted; one of the hazards of reading a standard, I guess.

    It would be a slightly interesting exercise to see if we can find a real compiler/library that, when it encounters this code...
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
         int *a, *b, *temp;
         temp = malloc(2*sizeof(int));
         a = temp;
         b = temp + 1;
         free(temp);
         if (b > a) fprintf(stdout, "Yes!");   /* undefined behaviour here */
         return 0;
    }
    does anything other than print "Yes!".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why does C need pointer conversion
    By password636 in forum C Programming
    Replies: 2
    Last Post: 04-10-2009, 07:33 AM
  2. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  3. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  4. scope of a pointer?
    By Syneris in forum C++ Programming
    Replies: 6
    Last Post: 12-29-2005, 09:40 PM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM