Hi all,
I know there's been a lot of articles and posts because of this malloc
and free combination and I've read quite a lot of them. Still I can't
get my program to work:
My Structure:
typedef struct rule {
char ip[IP_SIZE];
struct rule *next;
} rule_list;
My Function to add a rule to the list of rules:
void add_rule(rule_list **head, char* ip)
{
rule_list *tmp;
if ((tmp = malloc(sizeof(*tmp))) == NULL)
{
syslog(LOG_ERR, "malloc for inserting a new rule crashed! Out of
memory?");
exit(EXIT_FAILURE);
}
/* This is what doesn't work because the
compiler says incompatible types in assignment */
//tmp->ip = malloc(strlen(ip));
/* This would work (without the statement above, but without
allocating space for this member of the struct I can't free it later
on */
strcpy(tmp->ip, ip);
tmp->next = *head;
*head = tmp;
}
My Function to free the whole list including all members:
void freelist(rule_list *head)
{
rule_list *tmp;
printf("freeing the list...");
fflush(stdout);
while (head != NULL) {
printf("head is not null freeing its members...");
fflush(stdout);
/* This will crash on me any time I run it, since I haven't
allocated memory for it with malloc */
if (head->ip != NULL) free(head->ip);
tmp = head->next;
free(head);
head = tmp;
}
printf("list freed!...");
fflush(stdout);
}
I only made it so far:
1. I don't free() the member ip of the struct when freeing the whole
list
--> This will eat up more and more memory while the program is running
2. I try to free() the memory and it won't work --> crash!
What's still wrong here?
Thx a lot,
Kurt