Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =========MAIN.C============================================
- #include <stdlib.h>
- #include <stdio.h>
- #include "cstack.h"
- void printyay()
- {
- printf("Yay\n");
- }
- int main()
- {
- cstack *data=malloc(sizeof(cstack));
- typedef void (*fp)();
- fp callme=NULL;
- char buf[50], *message=NULL;
- int num=27,*newnum=NULL;
- sprintf(buf, "Hello there.\n");
- /* Push data into stack */
- cpush(&data, &printyay, sizeof(fp));
- cpush(&data, &num, sizeof(int));
- cpush(&data, &buf, sizeof(char)* 50);
- /* Pop from data */
- message=(char*)cpop(&data);
- newnum=(int*) cpop(&data);
- callme=(fp)cpop(&data);
- printf("%s%d\n", message, *newnum);
- callme(); //<--- ERROR! This causes a segmentation fault
- free(callme);
- free(message);
- free(newnum);
- free(data);
- return 0;
- }
- =========CSTACK.C==========================================
- #include "cstack.h"
- void cpush(cstack** stackp, void* data, int size)
- {
- (*stackp)->items++;
- (*stackp)->stack=realloc((*stackp)->stack, (*stackp)->items);
- (*stackp)->stack[(*stackp)->items-1]=malloc(size);
- memcpy(((*stackp)->stack)[(*stackp)->items-1], data, size);
- }
- void* cpop(cstack** stackp)
- {
- void* data=NULL;
- (*stackp)->items--;
- data=((*stackp)->stack)[(*stackp)->items];
- (*stackp)->stack=realloc((*stackp)->stack, (*stackp)->items);
- if((*stackp)->items==0)
- {
- free((*stackp)->stack);
- (*stackp)->stack=NULL;
- }
- return data;
- }
- =========CSTACK.H==========================================
- #ifndef _CSTACK_H_
- #define _CSTACK_H_
- #include <stdlib.h>
- #include <string.h>
- typedef struct cstack{
- void** stack;
- int items;
- }cstack;
- void cpush(cstack** stackp, void* data, int size);
- void* cpop(cstack** stackp);
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement