Date: Wed, 14 Jan 1998 13:23:09 +0200 (IST) From: Eli Zaretskii To: "Dr. András Sólyom" cc: djgpp AT delorie DOT com Subject: Re: Q: How to check validity of a pointer? In-Reply-To: <34BBF982.4525B8F9@eik.bme.hu> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Content-Transfer-Encoding: 8bit Precedence: bulk On Wed, 14 Jan 1998, Dr. András Sólyom wrote: > One of my programs keep crashing on realloc() and I cannot find the > reason. I suggest to post an example of a crash traceback (after running it through `symify'). It is possible that you are looking in the wrong direction. For example, if some function you call before `realloc' overwrites the EBP value saved on the stack, the following call to any function can crash with no apparent reason. The stack traceback will show this and other hints to the possible causes. You should always post it. > 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). `realloc' cannot possibly return pointers which cannot be accessed, unless they are NULL pointers. Are you sure the input to `realloc' is valid? Maybe it actually returns NULL, not 0x09000000? How did you display the values returned by `realloc'? Also, do the crashes happen inside `realloc' or after you use the pointers it returns? And btw, there's nothing invalid in the value of 0x09000000 as such, it is perfectly legal for `realloc' to return it. > 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. Do the other versions of `malloc' return the same value of 0x09000000 as well? If they do, it would suggest that `realloc' is not the problem. > So for debugging I can try to catch the invalid pointers. Is there > any way to check a pointer for validity before dereferencing it? You can do two things: 1) Compare the pointer with the DS selector limit, which should be returned by __dpmi_get_segment_limit(_my_ds()). If the pointer exceeds this value, or if it is less than 0x1000, it is invalid and will cause a crash. 2) Install a handler for the signal SIGSEGV and try to do something useful in the handler, like print some variables that will allow you to understand what's going on, before you exit. (You *must* exit from a SIGSEGV handler; if you return, the program will be aborted anyway.) I would probably do both of the above, since a pointer can be less than the limit and still be invalid (it's a long story).