Pushing data from a structure into a stack in C -


the task of program push data structure stack, using memcpy. upon execution, enters data structure, reaches segmentation fault when comes push() function.

here's code:

#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <mem.h>  typedef struct std {    char ime [50];    int fn;    float usp;    } std;    typedef struct stack {     std *s;     stack *next;      } stack;   int push (void *a, int siz,  stack **sst) { stack *snew; snew = (stack *) malloc (siz + 1); memcpy (snew->s, a, siz);   snew -> next = *sst;  *sst = snew;    }  int main () { stack *st; std  ss;  printf ("vyvedi ime"); gets (ss.ime); ss.ime[49] = 0; printf ("vyvedi fn"); scanf ("%d", &ss.fn);  printf ("vyvedi usp"); scanf ("%f", &ss.usp);    push (&ss, sizeof(ss) , &st);    system ("pause");      } 

don't know if matters, use devc compiler.

this code wrong:

stack *snew; snew = (stack *) malloc (siz + 1); memcpy (snew->s, a, siz);  

snew->s not initialized when memcpy a it. expect see 2 mallocs - 1 stack* , std*, use seed snew->s before copying stuff it.

stack *snew; snew = (stack *) malloc (sizeof(stack)); snew->s = (std*) malloc(sizeof(std)); memcpy (snew->s, a, siz); 

alternatively use single malloc, , point snew->s appropriate offset within (after you've left space stack struct).

stack *snew; snew = (stack *) malloc (sizeof(stack) + siz + 1); snew->s = (char*)snew + sizeof(stack); memcpy (snew->s, a, siz); 

the siz parameter on push function seems superfluous, since passing in struct std.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -