Normally making a copy of a struct is as simple as just using the = operator and the compiler generates code to copy the struct over for you. However, for this part the function has to return a pointer to a struct so I’ve been working with that the whole time only to get to a part where I realized that everything I tried wasn’t copying the struct over correctly.
A basic example of my problem is
typedef struct command_stream *command_stream_t;
command_stream_t ty = (command_stream_t) malloc(sizeof(struct command_stream));
command_stream_t yy;
do some code
//ty contains a variable words which is an array of strings
*yy = *ty;
ty->words = NULL; //set to null to see if yy still contains a copy of the struct
printf("%s", yy->words[0]);
I get a segmentation fault here. However, if I change it so it isn’t a pointer
typedef struct command_stream command_stream_t
yy=ty;
ty.words = NULL;
printf("%s", yy.words[0]);
This works just fine! I’m not entirely sure how I should do the same thing for pointers, and I don’t really want to go back and change 500+ codes of lines…
Your
yypointer is never initialized.You should allocate enough memory there to hold the struct and then either copy with * like you did, or use
memcpywith the pointers and size.