Search code examples
cdynamic-memory-allocationrealloc

Realloc Arguments


I am implementing Stack using arrays with the below code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Stack{
int top;
int capacity;
int *array;
};

struct Stack *createStack()
{
        struct Stack *stack=malloc(sizeof(struct Stack));
        stack->top=-1;
        stack->capacity=1;
        stack->array=malloc(sizeof(sizeof(int)*stack->capacity));
}
void doubleStack(struct Stack *stack)
{
        stack->capacity=stack->capacity*2;
        stack->array=realloc(stack,stack->capacity);
}
void push( struct Stack *stack , int data)
{
        if(stack->top==(stack->capacity)-1)
                doubleStack(stack);
        stack->array[++stack->top]=data;
}

My doubt is, when doubleStack is called once the Stack is full, Should I use stack->array as the first argument of the realloc() or stack as the first argument of the realloc()?

Well I think stack->array should be passed. As we need to reallocate only that portion of the memory.

But accidentally I passed stack and that also seemed to work. Please advise.


Solution

  • You should pass to realloc a pointer to the array that you wish to extend. Since stack is not an array that you wish to extend, and stack->array is, you should pass stack->array as the first parameter.

    However, you should store the result of realloc in a separate variable and do NULL check.

    If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).

    Otherwise you risk creating a memory leak:

    int *tmp = realloc(stack->array, stack->capacity);
    if (tmp) {
        stack->array = tmp;
    } else {
        ... // Deal with the allocation error here
    }