Advertisement
Guest User

Untitled

a guest
Aug 1st, 2009
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. =========MAIN.C============================================
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include "cstack.h"
  5.  
  6. void printyay()
  7. {
  8.   printf("Yay\n");
  9. }
  10.  
  11. int main()
  12. {
  13.   cstack *data=malloc(sizeof(cstack));
  14.   typedef void (*fp)();
  15.  
  16.   fp callme=NULL;
  17.  
  18.   char buf[50], *message=NULL;
  19.   int num=27,*newnum=NULL;
  20.  
  21.   sprintf(buf, "Hello there.\n");
  22.  
  23.   /* Push data into stack */
  24.   cpush(&data, &printyay, sizeof(fp));
  25.   cpush(&data, &num, sizeof(int));
  26.   cpush(&data, &buf, sizeof(char)* 50);
  27.  
  28.   /* Pop from data */
  29.   message=(char*)cpop(&data);
  30.   newnum=(int*) cpop(&data);
  31.   callme=(fp)cpop(&data);
  32.  
  33.   printf("%s%d\n", message, *newnum);
  34.   callme(); //<--- ERROR! This causes a segmentation fault
  35.  
  36.   free(callme);
  37.   free(message);
  38.   free(newnum);
  39.   free(data);
  40.   return 0;
  41. }
  42.  
  43. =========CSTACK.C==========================================
  44. #include "cstack.h"
  45.  
  46. void cpush(cstack** stackp, void* data, int size)
  47. {
  48.   (*stackp)->items++;
  49.   (*stackp)->stack=realloc((*stackp)->stack, (*stackp)->items);
  50.   (*stackp)->stack[(*stackp)->items-1]=malloc(size);
  51.   memcpy(((*stackp)->stack)[(*stackp)->items-1], data, size);
  52.  
  53.  
  54. }
  55.  
  56. void* cpop(cstack** stackp)
  57. {
  58.   void* data=NULL;
  59.   (*stackp)->items--;
  60.   data=((*stackp)->stack)[(*stackp)->items];
  61.   (*stackp)->stack=realloc((*stackp)->stack, (*stackp)->items);
  62.   if((*stackp)->items==0)
  63.     {
  64.     free((*stackp)->stack);
  65.     (*stackp)->stack=NULL;
  66.     }
  67.   return data;
  68. }
  69.  
  70. =========CSTACK.H==========================================
  71. #ifndef _CSTACK_H_
  72. #define _CSTACK_H_
  73. #include <stdlib.h>
  74. #include <string.h>
  75. typedef struct cstack{
  76.   void** stack;
  77.   int items;
  78. }cstack;
  79.  
  80. void cpush(cstack** stackp, void* data, int size);
  81. void* cpop(cstack** stackp);
  82.  
  83. #endif
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement