gb******@excite.com wrote On 02/21/06 15:50,:
I'm working on some legacy code and came across something like this.
Anybody know exactly what the ramifications are to the memory if you do
something like this:
int somefunction (some arguments)
{
...
Mystructtype mystruct;
...
otherfunc(&mystruct); /* this one appears to load up the struct*/
...
free(&mystruct);
Right here, the program goes off the rails. The
memory for mystruct was not obtained from malloc() et
al., so attempting to release it with free() produces
undefined behavior.
It is pointless to ask "exactly what the ramifications
are" from the point of view of the C language: the language
says only that the consequences are undefined. As far as
the language is concerned, the program can do anything at
all; it is an outlaw in the sense that the laws no longer
apply to it.
The question may be answerable from the point of view
of a particular C implementation, but not in terms of
the language itself.
[...]
What would you do about it?
First, double- and triple-check that the code really,
truly does what your paraphrase says. Pay close attention
to indirection levels; note that the superficially similar
typedef struct s Mystructtype;
typedef Mystructptrtype *Mystructtype;
Mystructptrtype mystruct;
create (&mystruct);
...
destroy (&mystruct);
might be perfectly legitimate, given something like
void create (Mystructptrtype *ptr) {
*ptr = malloc(sizeof *ptr);
...
}
void destroy (Mystructptrtype *ptr) {
...
free (*ptr);
}
Examine the typedefs with particular care; when typedef is
used to create aliases for pointer types, the fact that
you're dealing with a multiple indirection can be less than
obvious. If it turns out that the code is in fact correct
but that the typedef names are muddying the waters, I'd
suggest getting rid of pointer typedefs and using just the
"base" types instead. Keep the typedef aliases for the
structs themselves, if you like (some people don't), but
get rid of the pointer typedefs based on them.
If it turns out that the code actually does what your
paraphrase says, you've got a problem: you need to read the
minds of the people who wrote the code and try to figure
out what in the world they were trying to accomplish. This
will require some ESP on your part, because the C doesn't
reveal their intentions -- as we've seen, the C as written
has no meaning and is therefore uninformative. Once you've
figured out what they were trying to do, rewrite the code so
it does that thing in some legitimate way.
Good luck!
--
Er*********@sun.com