Here is my code:
struct movie {
char movie_name[30];
float score;
struct movie *next;
};
typedef struct movie *p_movie;
void print_all(struct movie *head);
int main() {
p_movie head = NULL;
p_movie new_node = malloc(sizeof(struct movie));
if (new_node == NULL) {
exit(1);
}
strcpy(new_node->movie_name, "Avatar");
new_node->score = 9.5f;
new_node->next = NULL;
if (head == NULL)
head = new_node;
print_all(head);
new_node = malloc(sizeof(struct movie));
if (new_node == NULL) {
exit(1);
}
strcpy(new_node->movie_name, "Aladdin");
new_node->score = 8.0f;
new_node->next = NULL;
p_movie temp = head;
head = new_node;
new_node->next = temp;
print_all(head);
}
void print_all(struct movie *head) {
printf("---------------------\n");
printf("Head address = %zd\n", (size_t)head);
struct movie* search = head;
while (search != NULL) {
printf("%zd \"%s\" %f %zd\n", (size_t)search, search->movie_name,
search->score, (size_t)search->next);
search = search->next;
}
}
I'm confused because of malloc
: It runs well, but I don't know why this code is running well.
My question is about new_node
: first, I allocate memory to new_node
and I don't free that and allocate memory again.
Then, what's happening with the first memory (Avatar
)? Is that deleted? or saved somewhere..?