Monday, 15 April 2013

c - malloc call changing subroutine parameter struct's fields -



c - malloc call changing subroutine parameter struct's fields -

i implementing linked list of structs, getting odd error in subroutine call. have 2 structs, pupil , request follows:

9 struct request{ 10 char class_name[24]; 11 struct request * next_request; 12 }; 13 14 struct student{ 15 struct request * request_list; 16 int request_total; 17 struct pupil * next_student; 18 char name[24]; 19 };

and using subroutine phone call add together students request_list

104 void add_request(struct pupil * student, char* class_name){ 105 student->request_total = student->request_total+1; 106 printf("%s before\n", student->name); 107 fflush(stdout); 108 109 struct request * new_req = malloc(sizeof(struct request)); 110 110 printf("%s after\n", student->name); 110 fflush(stdout); 111 // other stuff ...

but malloc phone call changing pupil structs name fields next output:

bob before 1 after

does know causing this?

edit: stupid error on part, found it. new student, under specific condition, malloc()ing size of pupil pointer before subroutine call, rather student. still don't know why error occurring after line though, threw me off. help everyone.

you need @ calling add_request() , pupil pointer passed it. likely, memory pupil pointing not allocated or inadvertently freed before phone call add_request. passing pointer right element in linked list , not accidently passing pointer 1 discarded earlier?

while not causing issue, since declaring class name , pupil name arrays, may need consider may have pupil name or request name long array somewhere.

c struct

No comments:

Post a Comment