malloc() and free() and linked list

Discussion in 'C Programming' started by Kurt, Dec 16, 2004.

  1. Kurt

    Kurt Guest

    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

    /* 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...");

    while (head != NULL) {
    printf("head is not null freeing its members...");

    /* 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;
    head = tmp;
    printf("list freed!...");


    I only made it so far:
    1. I don't free() the member ip of the struct when freeing the whole
    --> 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, Dec 16, 2004
    1. Advertisements

  2. Excellent, I seems you have been reading up on this. :)
    You don't need the inner parentheses there i.e. sizeof *tmp is fine, but
    you can put them in if you like
    Saying "crashed" isn't quite right. Crashed suggests something like a seg
    fault whereas what happened here is that malloc() simply failed to perform
    the requested operation in a well defined way saying that it can't or
    won't do that.
    You can't assign to an array in C. The array you want is being created by
    malloc(), make the ip structure member a pointer so it can point to that

    There is another problem here in that strlen(ip) doesn't account for the
    terminating null character that every string requires. Make that
    strlen(ip)+1. Don't forget to test the return value of this malloc() for

    Lawrence Kirby, Dec 16, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.