0

I have a while loop, where in each itteration of the while loop I malloc a struct object. Then at the end of the loop I add it to the end of a linked list. Now my concern is, I have the same variable name when I malloc each time in the loop, so I dont understand how this works after I attach the lastest malloced object to the linked list, what happens to the others that I malloced that had the same name.

My code:

struct Student{ 
   char *name;
   int IDno;
}Student;

someFunction(){
x = 0;

while(x!=6){
    Student *name = malloc(sizeof(Student));   <----- Confusion here

    addToLinkedList(LinkedListStruct,name);
}

Is it alright that I have name being malloced each time in the loop. Can someone explain to me what happens if I malloc in this way, add it to the end of a linked list and then go into the next loop and do this same.

John
  • 105
  • 1
  • 8

1 Answers1

1

The malloc() call has no relationship to the name of the variable you assign its return value to. malloc() doesn't know that you assign its return value to a variable named name. What you do is completely valid and well-defined.

There is still an error with your code though as malloc() returns a pointer to a memory area, not the memory itself. Thus the declaration should have been

Student *name = malloc(sizeof (Student));
fuz
  • 88,405
  • 25
  • 200
  • 352
  • It's good practice the cast the result to the proper type, in this case `Student*`. – John Sensebe Jan 29 '16 at 15:57
  • 2
    It is actually **very bad** practice - http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Idos Jan 29 '16 at 15:58
  • @FUZxxl How would I free it later on, now that I have connected it to the end of a linked list? – John Jan 29 '16 at 16:04
  • @John Walk the linked list until you find the desired object and then call `free()` on the pointer. – fuz Jan 29 '16 at 16:06
  • 1
    @FUZxxl I hope you are not confusing `name` in the malloc statement with the `name` member of the Student struct - that pointer remains unassigned. And a better way of writing the malloc statement is `Student *pupil = malloc( sizeof (*pupil ) );` That makes it easier later on if you ever decide to change `Student` to some other more elaborate struct. – FredK Jan 29 '16 at 16:29
  • @FredK No, I was not confusing these two. What gives you this idea? – fuz Jan 29 '16 at 17:13