Re: Does malloc() reuse addresses?




avasilev wrote:
Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid(myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.

If you are doing what you say with the instance array, why are you not
removing the pointer from the array when you free the element of the
list. Sounds like you might want to rethink your design a little.

.



Relevant Pages

  • Re: problems with free()
    ... No need to initialize mystr to NULL, ... you could just as easily put the malloc ... printf("Could not allocate memory"); ... array into the pointer object mystr. ...
    (comp.lang.c.moderated)
  • Re: Are the following 2 code statements equivalent
    ... In the calloc() case, the ... is not allowed to allocate some smaller amount. ... You call memsetwithout checking the result of the malloc() call. ... If mallocfails, it returns a null pointer, and the call to memset ...
    (comp.lang.c)
  • Re: malloc inside function (I know... I *did* search google first ;)
    ... > and the return value of malloc should ALWAYS be checked for NULL, ... Functions that allocate memory commonly return a pointer to the memory ... and then the float * return is certainly more natural ...
    (comp.lang.c)
  • freeing memory....partially
    ... i would like to allocate two structures making only one malloc call. ... These two pointer are later used by two threads in mutual exclusion so ... Remember that i cannot use realloc beacause thread2 cannot access ptr1. ...
    (comp.lang.c)
  • Does malloc() reuse addresses?
    ... if i allocate some memory with malloc() and later free it (using ... allocate memort at the same starting address and will return the same ... int isInstanceValid ... In this example, if an instance is freed, and a pointer to it becomes ...
    (comp.lang.c)

Loading