This is my first attempt at writing a C program, it a generic stack that can grow accordingly. It appears to work correctly, however I am worried that is just a fluke and I could be doing something very wrong.
I would greatly appreciate any feedback/criticism.
I am aware I should split this out into a .h and .c file but for demonstration purposes I have listed it as one.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Stack
{
void** data;
int capacity;
int count;
} Stack;
void stack_init(Stack *stack, int capacity)
{
stack->data = (void**)malloc(capacity * sizeof(void*));
stack->capacity = capacity;
stack->count = 0;
}
void stack_push(Stack *stack, void* entry)
{
if (stack->count >= stack->capacity)
{
stack->capacity *= 2;
stack->data = (void**)realloc(stack->data, stack->capacity * sizeof(void*));
}
stack->data[stack->count] = entry;
stack->count++;
}
void* stack_pop(Stack *stack)
{
stack->count--;
return stack->data[stack->count];
}
bool stack_is_empty(Stack *stack)
{
return (stack->count == 0);
}
int main()
{
Stack myStack;
stack_init(&myStack, 2);
for (int i = 0; i < 2; i++)
{
stack_push(&myStack, i);
}
while (!stack_is_empty(&myStack))
{
printf("%d\n", (int)stack_pop(&myStack));
}
return 0;
}
double
or any kind ofstruct
this code will fail spectacularly.. What you're doing is wrong.void*
looses any type information, including the size of the original type. Thussizeof(void*)
for allocation is futile from the beginning. You're allocating space for a pointer size. \$\endgroup\$void*
space to store anint
under the assumption thatsizeof(int) <= sizeof(void*)
. The practice of (ab)using the genericvoid*
data itself to store the value instead of pointing to an external data block (and thus worrying about lifetime) is common in C. \$\endgroup\$int
values only, and makes the stack interface quite confusing. \$\endgroup\$