David said:
Hi friends, is there a way to know if an object doesn't need to be
freed or is allocated using malloc? any tip is welcome
Yes. Keep track of it when you allocate it.
The way to do this is to use the concept of ownership of memory. At all
times during the lifetime of a block of allocated memory, you should
always have one and only one pointer that "owns" that block. Other
pointers may point into that block, but only the owning pointer should
ever be passed to free().
If at all possible, an owning pointer should be reserved for the purpose
of owning pointers; it should not be used to store pointers to memory it
does not own. I generally try to arrange that an owning pointer is
initialized with a call to malloc(); if that's not feasible, it should
be set to NULL sometime before first use. I also try to make sure that
the lifetime of an owning pointer ends immediately after I free() the
memory it owns. However, when that's not possible, set it to NULL
immediately after free()ing that memory. With those precautions in
place, you should not let the lifetime of a non-null owning pointer end
without first passing it to free().
If you have trouble keeping track of which pointers are 'owning'
pointers, put a comment about that fact next to their declaration. If
you have lots of trouble, use a naming convention to keep track of this
feature.
If, for any reason, it is not possible to reserve an owning pointer
variable exclusively for ownership of the memory it points at, you
should set aside a separate flag variable to keep track of whether or
not that pointer currently owns the memory it points at. Creating a
struct that contains both the pointer and the ownership flag is a very
natural way to handle this - it ensures that they don't get separated.
If you have a rather complicated program, it may be necessary to
transfer ownership of memory from one owning pointer variable to
another. If so, make sure that any memory owned by target pointer is
free()d before the transfer, and unless the lifetime of the source
pointer ends immediately after the transfer, set the source pointer to
NULL. If you're using ownership flags, reset them accordingly.