All about programming in GNU/LINUX

Functions to avoid heap overflow while using Dynamically Allocated Arrays like int *v,char **h,char t[].(this code is type specific for ints)

typedef struct
{
 int *elems;
 int loglength;
 int alloclength;
}stack;

void stacknew(stack *s);
void stackdispose(stack *s);
void push(stack *s,int value);
void pop(stack *s);

void stacknew(stack *s)
{
 s->loglength=0;
 s->alloclength=4;
 s->elems=malloc(4*sizeof(int));
 assert(s->elems!=NULL);
}

void stackdispose(stack *s)
{
 free(s->elems);
}

void stackpush(stack *s,int value)
{
 if(s->loglength==s->alloclength)
 {
  s->elems=realloc(s->elems,4*sizeof(alloclength));
  assert(s->elems!=NULL);
 }
 s->elems[loglength]=value;
 s->loglength++;
}

void pop(stack *s)
{
    assert(loglength>0);
    loglength--;
    return s->elems[loglength];//Identify the error
}



Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s