user123
user123

Reputation: 301

when is realloc() equivalent to malloc() in C?

In this code snippet ,realloc is equivalent to malloc but I am unable to get the logic .

int *ptr=(int*) realloc(NULL,10*sizeof(int));

why does it creates a new block , since NULL is a macro defined in stdio.h as 0 so it implies that it points to the base address 0 which in most machines is system area , so how can realloc start allocating a memory from base address 0 for 10 integers , why is this not a segmentation fault ?

Upvotes: 2

Views: 849

Answers (4)

dlmeetei
dlmeetei

Reputation: 10391

Yet another answer, All have explained beautifully but misses some good observation.

The following behaviour is taken from Linux man. You might like read doc for your platform. realloc(void *ptr, size_t size) has been to have a bad design, trying to perform many task, for instance

1) if ptr == NULL, it behaves like malloc(size)

2) if ptr != NULL && size == 0, it behaves like free(ptr)

More details at man 3 realloc.

So, it is preferable to have a wrapper for realloc especially for usage like ptr = realloc(ptr, size); which leads to leak.

void* my_realloc(void *oldPtr, size_t newSize)
{
    void *newPtr = NULL;
    if ( (newPtr = realloc( oldPtr, newSize) ) == NULL) 
    {
        free( oldPtr);
        return NULL;
    }
    return newPtr;
}

Upvotes: 0

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

To clarify: it means the function realloc checks if its first argument is 0 (a NULL pointer) and if yes, behaves like malloc or simply calls malloc.

Upvotes: 3

tdao
tdao

Reputation: 17713

so how can realloc start allocating a memory from base address 0

From realloc manual:

In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.

So in case the previous pointer is NULL, it doesn't mean that realloc has to start allocating from base address 0. In fact, it will behave like malloc, allocating a new block of memory.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122493

NULL is a macro defined in stdio.h as 0 so it implies that it points to the base address 0

That's not true. NULL is the macro for the null pointer, which doesn't necessarily point to base address 0. See C FAQ.


To answer your main question, realloc behaves like malloc when the first argument is the null pointer.

Upvotes: 2

Related Questions