ting to Generic stack implementation in C with void pointers -
trying implement simple generic stack went trough bunch of stack overflows , segmentation faults wrote this:
#include <stdlib.h> #include <stdio.h> #define nullptr (void *)0 struct s { void *content; struct s *next; }; typedef struct s stack; stack *createstack() { stack *tmp = (stack *) malloc(sizeof(stack)); tmp->content = nullptr; tmp->next = nullptr; return tmp; } stack *pushstack(stack *ptr, void *content) { stack *newstr = createstack(); newstr->content = content; newstr->next = ptr; ptr = newstr; return (ptr); } stack *popstack(stack *ptr, void *value) { stack *todelete = ptr; value = ptr->content; ptr = ptr->next; free(todelete); return (ptr); } stack *stackhandle = nullptr; void printstack(stack *ptr) { int *element; int i; for(i=0; <= 20; i++) { ptr = popstack(ptr, element); printf("%d ", *element); } printf("\n"); } int main() { stackhandle = createstack(); int i; for(i=0; <= 21; i++) { stackhandle = pushstack(stackhandle, &i); } printstack(stackhandle); }
everything works fails restore int void pointer... analyzing other implementations i'm still not understanding why mine not working. here expecting see 21
times getting instead
0 8240 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056 842539056
for every value of bigger 20 , beautiful segmentation fault if below 20
you aren't allocating space hold actual data, allocating room pointers point elsewhere. that's not useful adt.
what instead create stack holds hard-copies of data:
typedef struct s { void* data; size_t size; struct s* next; } stack;
the functions have changed:
stack *pushstack(stack *ptr, void *data, size_t size); stack *popstack(stack *ptr, void *data, size_t* size); // return data , size
you instead create item this:
stack *createstack (void* data, size_t size) { stack *tmp = malloc(sizeof(stack)); tmp->data = malloc(size); memcpy(tmp->data, data, size); tmp->size = size; tmp->next = null; return tmp; }
once have changed design above, can start worrying weeding out bugs.
Comments
Post a Comment