I have some problem. I need to write function (ft_list_clear), that delete all elements from selected element in linked list. The function is work correctly: after using this function, data not in the list, but still available in other data. Let me show.
My main.c:
#include <stdlib.h>
#include "hd.h"
#include "ft.c"
t_list *ft_create_elem(void *data)
t_list *ft_list_push_params(int arc, char **arv);
void ft_list_clear(t_list **head);
void print_pointer(void *data)
{
printf("%s ", *&data);
}
void print_linked_list(t_list *head)
{
t_list *node = head;
while (node)
{
print_pointer(node->data);
node = node->next;
}
printf("\n");
}
int main(int argc, char **argv)
{
head1 = ft_list_push_params(argc, argv);
print_linked_list(head1);
void *link1 = head1->data;
void *link2 = head1->next->data;
void *link3 = head1->next->next->data;
void *link4 = head1->next->next->next->data;
print_pointer(link1);
print_pointer(link2);
print_pointer(link3);
print_pointer(link4);
printf("\n");
ft_list_clear(&head1);
printf("cleared\n");
print_pointer(link1);
print_pointer(link2);
print_pointer(link3);
print_pointer(link4);
printf("\n");
print_linked_list(head1);
return 0;
}
My ft.c:
#include "hd.h"
t_list *ft_create_elem(void *data)
{
t_list *node;
if (!(node = malloc(sizeof(t_list))))
return (0);
node->data = data;
node->next = 0;
return (node);
}
void ft_list_push_front(t_list **head, void *data)
{
t_list *node;
if (!(*head))
*head = ft_create_elem(data);
else
{
node = ft_create_elem(data);
node->next = *head;
*head = node;
}
}
t_list *ft_list_push_params(int ac, char **av)
{
t_list *head;
int i;
i = 1;
head = 0;
while (i < ac)
{
ft_list_push_front(&head,av[i]);
i++;
}
return (head);
}
void ft_list_clear(t_list **begin_list)
{
if (*begin_list && (*begin_list)->next)
ft_list_clear(&(*begin_list)->next);
free(*begin_list);
*begin_list = 0;
}
And header:
#ifndef FT_LIST_H
# define FT_LIST_H
typedef struct s_list
{
struct s_list *next;
void *data;
} t_list;
#endif
code to run:
gcc main.c | ./a.out 111 222 333 444 | cat -e
Int this case i have followed output:
444 333 222 111 $
cleared$
444 333 222 111 $
$
So, I've got a question: why string with "444 333..." is printed second time. I have free this memory. Of not? Why data at *linkN still available?
Added:: Lundin, geniously. I think that may be marked as answer. But how can i check that without printing? How someone can exam me in this question? My task - make "free" function. What if i say (head = 0)? It is not solution, but same result in my mind. Thanks to Andrew Henle for explanations.