I'm trying to create a stack library from scratch. It stores generic elements which are passed in void* pointers.
This is the defined structure:
typedef struct stackObject
{
void* obj;
struct stackObject *next;
} StackObject_t;
typedef struct stackMeta
{
StackObject_t *stack;
size_t objsize;
int numelem;
} StackMeta_t;
So far I have implemented the following:
#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
/* Creates a stack of c objects of size objsize and returns
* a handle (pointer) to the just created stack. On error,
* NULL is returned.*/
StackMeta_t *mystack_create(size_t objsize)
{
StackMeta_t *newstack = malloc(sizeof(StackMeta_t));
if(newstack != NULL && objsize > 0){
newstack->stack = NULL;
newstack->objsize = objsize;
newstack->numelem = 0;
return newstack;
}
else{
return NULL;
}
}
/* Pushes an object to the stack identified by its handle
* returns 0 on success and -1 on an error*/
int mystack_push(StackMeta_t *stack, void* obj)
{
/* pointer to new object */
StackObject_t *newObj = malloc(sizeof(StackObject_t));
newObj->obj = malloc(stack->objsize);
if(newObj != NULL){
newObj->obj = memcpy(newObj->obj, obj, stack->objsize);
newObj->next = stack->stack;
stack->stack = newObj;
stack->numelem++;
return 0;
}
else{ /* no space available */
return-1;
}
}
/* Pops an object from the stack identified by its handle
* returns 0 on success and -1 on an error*/
int mystack_pop(StackMeta_t *stack, void* obj)
{
StackObject_t *tempObj = stack->stack;
if(tempObj != NULL){
obj = memcpy(obj, tempObj->obj, stack->objsize);
stack->stack = tempObj->next;
stack->numelem--;
free(tempObj->obj);
free(tempObj);
return 0;
}
else{
return -1;
}
}
/* Destroys and cleans the stack handle */
void mystack_destroy(StackMeta_t *stack)
{
StackObject_t *tempObj = stack->stack;
StackObject_t *nextObj = NULL;
while(tempObj != NULL){
nextObj = tempObj->next;
free(tempObj->obj);
free(tempObj);
tempObj = nextObj;
}
stack = NULL;
}
/* Returns number of elements of the stack or -1 if invalid handle*/
int mystack_nofelem(StackMeta_t *stack)
{
if(stack != NULL){
return stack->numelem;
}
return -1;
}
objsizeparameter? It seems to be unused, as you only store pointers to the objects. \$\endgroup\$