Kurt wrote:
> 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;
In the typedef, you have allocated space for the member ip with:
char ip[IP_SIZE];
The question is what is IP_SIZE?
> 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));
Correct. tmp->ip is an array IP_SIZE characters. You do not
need to dynamically allocate space.
> /* 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);
Mignt want to use function strncpy.
strncpy(tmp->ip,ip,IP_SIZE);
tmp->ip[IP_SIZE-1] = '\0';
> 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);
Yes, Since you have not dynamically allocated the ip member.
You do not need to free it.
> tmp = head->next;
> free(head);
> head = tmp;
> }
> printf("list freed!...");
> fflush(stdout);
>
> }
>
> What's still wrong here?
Here is the corrected code ans usage:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define IP_SIZE 32
typedef struct rule
{
char ip[IP_SIZE];
struct rule *next;
} rule_list;
int add_rule(rule_list **head, const char* ip)
{
rule_list *tmp;
tmp = malloc(sizeof *tmp);
if(tmp)
{
strncpy(tmp->ip, ip, IP_SIZE);
tmp->ip[IP_SIZE-1] = '\0';
tmp->next = *head;
*head = tmp;
}
return tmp?1:0;
}
void freelist(rule_list **head)
{
rule_list *tmp;
while (*head != NULL)
{
tmp = (*head)->next;
free(*head);
*head = tmp;
}
return;
}
int main(void)
{
rule_list *head = NULL, *tmp;
add_rule(&head,"192.168.001.001");
add_rule(&head,"192.168.001.007");
puts("The ips in the list are:");
for(tmp = head; tmp; tmp = tmp->next)
puts(tmp->ip);
freelist(&head);
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto:
(remove the x to send email)
http://www.geocities.com/abowers822/