All about programming in GNU/LINUX

A generic code for preventing Overflow in Stacks when dynamic arrays used .(Just the functions are provided for now m will publish a sample soon)

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<assert.h>
typedef struct
{
 void *elems;
 int elementsize;
 int loglength;
 int alloclength;
}stack;

void stacknew(stack *s,int elemsize);
void stackdispose(stack *s);
void push(stack *s,void *elemaddr);
void pop(stack *s,void *elemaddr);
static void stackgrow(stack *s);
void stacknew(stack *s,int elemsize)
{
 s->elementsize=elemsize;
 s->loglength=0;
 s->alloclength=4;
 s->elems=malloc(4*sizeof(elemsize));
 assert(s->elems!=NULL);
}
void stackdispose(stack *s)
{
 free(s->elems);

}
void push(stack *s,void *elemaddr)
{
     if(s->loglength==s->alloclength)
      stackgrow(s);
    void *target=(char *)s->elems+(s->loglength*s->elementsize);
    memcpy(target,elemaddr,s->elementsize);
    s->loglength++;
}
static void stackgrow(stack *s)
{
    s->alloclength*=2;
    s->elems= realloc(s->elems,s->elementsize * s->alloclength);
    assert(s->elems!=NULL);
}

void pop(stack *s,void *elemaddr)
{   int temp=s->loglength-1;
    assert(s->loglength>0);
    void *source=(char *)s->elems+temp*s->elementsize;
    memcpy(elemaddr,source,s->elementsize);
    s->loglength--;
}

int main()
{
 char *names []={"HI","BOB","BYE"};
 int i;

 stack stringstack;
 stacknew(&stringstack,sizeof(char *));
 for( i=0;i<3;i++)
 {
  char *cpy=strdup(names[i]);
 push(&stringstack,&cpy);
 }
 char *name;
 for( i=0;i<3;i++)
 {
  pop(&stringstack,&name);
  printf("\n%s",name);
  free(name);
 }
 stackdispose(&stringstack);
 return 0;
 }
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