Sebastian Cadena
Sebastian Cadena

Reputation: 1

Is there any difference between allocating realloc() to a different pointer and allocating realloc() to the same one?

I´m kind of new to using dynamic memory in C and I was wondering if there was any diference between using realloc() to allocate to a different pointer and using realloc() to allocate the same pointer. For example:

int *ptr = calloc(10,sizeof(int))
ptr=(int*)realloc(ptr,20);

and

*ptr3;
int *ptr = calloc(10,sizeof(int))
ptr3=(int*)realloc(ptr,20);

I´ve already executed both codes and I see no real diference between both codes (nor between the values of the opinters nor the memory allocations). Thank you.

Upvotes: 0

Views: 549

Answers (2)

WBuck
WBuck

Reputation: 5501

For the first case, if realloc fails it returns a null pointer. You would then be assigning that null pointer to ptr making it impossible to free the memory that was originally pointed to by ptr.

Instead, do something like below:

int* p = malloc( 10 * sizeof( int ) );

/* Take note of the memory size I'm requesting in the 
   realloc call compared to yours. */

int* tmp = NULL;
if ( ( tmp = realloc( p, 20 * sizeof( int ) ) ) == NULL ) {
    /* We failed to find available memory, but we're 
       still on the hook for freeing the memory pointed to by p. */

    free( p );
    return;
}

/* We were successful in either extending the memory pointed to by p
   or a new block of memory was allocated for us and the memory pointed to by p
   was copied over for us. In either case, you do not have to free p
   before assigning tmp to p. */

p = tmp;

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155574

The difference occurs in the former case when realloc fails; in that case, it returns NULL, but doesn't free the original ptr you passed it. By directly reassigning ptr, you guarantee a memory leak when realloc fails, because you no longer have the original pointer to free.

The canonical/correct usage seen here uses two pointers, one persistent, one as a temporary. The result of realloc is always put in the temporary so it can be checked (and the persistent pointer free on failure). After reallocation is known to have succeeded, the temporary pointer replaces the persistent (which is guaranteed to either be the same as the temporary, or if the allocation could not be done in place, invalid).

Upvotes: 2

Related Questions