The task of the program is to push all the data from a structure into a stack, using memcpy.
Upon execution, it successfully enters the data into the structure, but reaches a segmentation fault when it comes to the push() function.
Here’s the 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 it matters, I use DevC as a compiler.
This code is wrong:
snew->sis not initialized when youmemcpy ainto it. I would expect to see twomallocs – one forSTACK*and another forSTD*, which you would then use to seedsnew->sbefore copying stuff into it.Alternatively you could use a single
malloc, and pointsnew->sto the appropriate offset within it (after you’ve left space for theSTACK struct).The
sizparameter on yourpushfunction seems superfluous, since you are always passing in astruct STD.