HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

implementation of a stack in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationstackstackoverflow

Problem

Below is my implementation of a stack in C. Is it correct? And/or is there anything that I should fix to make it better in any way?

stack.h

#ifndef STACK_H
#define STACK_H

#define EMPTY_STACK -1
typedef struct stack
{
  char ch;
  struct stack* prev;
} Stack;

extern Stack* init_stack(void);
extern char pop(Stack*);
extern void push(Stack*, char);

#endif


stack.c

#include "stack.h"
#include "stdlib.h"

Stack* init_stack()
{
  Stack* ret = (struct stack*)malloc(sizeof(struct stack));
  ret->prev = NULL;
  return ret;
}

char pop (Stack* stck)
{
  char ret;
  if (stck->prev)
  {
    ret = stck->ch;
    Stack* prv = stck->prev;
    stck->prev = prv->prev;
    stck->ch = prv->ch;
    free(prv);
    return ret;
  }
  else
    return EMPTY_STACK;
}

void push (Stack* stck, char ch)
{
  Stack* new_nd = (struct stack*)malloc(sizeof(struct stack));

  new_nd->prev = stck->prev;
  new_nd->ch = stck->ch;

  stck->prev = new_nd;
  stck->ch = ch;
}


Thanks!

Solution

I would advise you not implementing stacks with a linked list because for each char of info you consume 2 sizeof(void) because of memory alignment in your struct.

Because of this you won't be able to handle a big amount of data.

What happens if you push EMPTY_STACK ? Your pop will return a false EMPTY_STACK when going through the if. Isn't there a better way to handle this ?

Context

StackExchange Code Review Q#16134, answer score: 6

Revisions (0)

No revisions yet.