banu <va***********@gmail.comwrites:
On Oct 3, 2:38 pm, frakie <frakie...@gmail.comwrote:
>is there a method to check if a pointer is pointing a freed memory
location?
I think the question is whether its is possible to test if a
pointer(initialized explicitly or has a random garbage)is pointing to
freed memory i.e memory which is not part of the current process in
execution.
Although I don't know the std library function or code for this, but
work around would be to find out the absolute memory address space for
the program in execution. This would involve finding address range
for code segment (cs), data segment (ds) and stack. Once u have the
address range, u can test the address value stored in pointer against
the address range and take decision accordingly.
Maybe I am not fully correct with the solution, but It seems right to
me at least logically.
Please don't use silly abbreviations like "u" for "you".
Standard C has no concept of code segment, data segment, or stack.
Any program that depends on such things is not going to be portable,
and could easily break even between one version of the compiler or OS
and the next.
Checking ranges of addresses, even if it's possible, isn't going to
solve the problem anyway. Just examining the value of a freed pointer
invokes undefined behavior; it's likely to be harmless on most
implementations, but a system *could* check a pointer value for
validity when loading it into a register, and trap if it's invalid.
Even if you can safely examine indeterminate pointer values, the fact
that allocated memory can be re-used causes problems. For example:
some_type *ptr1, *ptr2;
ptr1 = malloc(sizeof *ptr1);
/* ... */
free(ptr1);
/*
* ptr1 now has an indeterminate value
*/
ptr2 = malloc(sizeof *ptr2);
/*
* malloc() could easily re-use the same chunk of memory that was
* used for ptr1. Any test on the value of ptr1 would falsely
* indicate that it points to a valid chunk of memory.
*/
The only real solution is to keep track of it yourself.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"