c - Realloc Arguments -


i implementing stack using arrays 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 called once stack full, should use stack->array first argument of realloc() or stack first argument of realloc()?

well think stack->array should passed. need reallocate portion of memory.

but accidentally passed stack , seemed work. please advise.

you should pass realloc pointer array wish extend. since stack not array wish extend, , stack->array is, should pass stack->array first parameter.

however, should store result of realloc in separate variable , null check.

if function fails allocate requested block of memory, null pointer returned, , memory block pointed argument ptr not deallocated (it still valid, , contents unchanged).

otherwise risk creating memory leak:

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

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -