www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/13/20:32:41

From: flux AT stack DOT nl (Mark van der Aalst)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Q: How to check validity of a pointer?
Date: 14 Jan 1998 02:10:16 +0100
Organization: MCGV Stack, Eindhoven University of Technology, the Netherlands.
Lines: 68
Message-ID: <69h39o$spu@toad.stack.nl>
References: <34BBF982 DOT 4525B8F9 AT eik DOT bme DOT hu>
NNTP-Posting-Host: toad.stack.nl
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Dr. András Sólyom (solyom AT eik DOT bme DOT hu) wrote:
> One of my programs keep crashing on realloc() and I cannot find the
> reason. I am allocating and reallocating some million times and somehow
> some pointers in the program which were valid becomes invalid, usually
> having a value of 0x09000000). I have tried many things (like using one
> of DJ's malloc()'s, or compiling under linux with ElectricFence) to
> catch the error but without success. So for debugging I can try to catch
> the invalid pointers.
> Is there any way to check a pointer for validity before dereferencing
> it?

realloc() will return NULL if the call failed, meaning if ;

char *bar = malloc(12);
char *foo = realloc(bar, 24);

if(!foo) printf("Hey realloc() failed !");

There are a couple of things to note ;

1. the pointer to foo might not be the same as bar. (e.g. realloc()
is allowed to change the pointer)
2. If the call failed (e.g. returns NULL) bar will still be valid
but foo will not.
3. bar *must* be alloced using either malloc(), calloc() or realloc()
   and may not point to freed memory (but may be a NULL pointer).

I'd suggest to write your own realloc() and do additional chenking on it,
e.g. :

/* from the top of my head */

#include <stdlib.h> /* important */

void *my_realloc(void *p, size_t size)
{
  void *bar ;

  if(!p) /* valid - but warn anyway */
   {
     fprintf(stderr, "calling realloc() with NULL ptr\n");
       
     return malloc(size);
   }
 
  if(!size) /* valid - but warn anyway */
   {
     fprintf(stderr, "calling realloc() with 0 size\n");

     free(p); 

     return NULL ;
   }

 bar = realloc(p, size);

 if(!bar) /* oops, it failed */
  {
    fprintf(stderr, "damn\n");

    abort();  
  }  

 return bar ;
}


Cheers, flux.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019