Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Can't initate a pointer that is passed as an argument

#include <stdio.h>
#include <stdlib.h>
typedef struct {
    unsigned length;
} List;
void init(List *l) {
    l = (List *) malloc(sizeof(List));
    l->length = 3;
}
int main(void) {
    List *list = NULL;
    init(list);
    if(list != NULL) {
        printf("length final %d \n", list->length);
        return 0;
    }
    return 1;
}

This is a simplified version of the code that is giving me problems. I am trying to construct the pointer *list from a method where *list is passed as an parameter.

I know I can make void init(List *l) work by changing it to void init(List **l) but this is for a class tutorial. I can't change the method arguments. I have spent four hours working on this.

I want to ensure that there is no way to make void init(List *l) work before I confront my professor.

Thanks in advance

like image 588
Brooks B Avatar asked Feb 10 '11 06:02

Brooks B


1 Answers

You're passing a copy of the pointer to init, which is allocating memory, storing it in its local copy, and promptly leaking it when init returns. You cannot pass data back to the calling function this way. You need to either return the allocated data, or pass in a pointer to the pointer you want to modify, both of which involve modifying the function signature.

void init(List **l) {
    *l = (List *) malloc(sizeof(List));
    (*l)->length = 3;
}

init(&list);

Did the assignment specify that you have to allocate the List from within init? If not, you could always pass a pointer to an already allocated List object, and perform whatever initialization length = 3 is a place-holder for:

void init(List *l) {
  l->length = 3;
}

List list;
init(&list);
printf("length final %d \n", list.length);
like image 181
meagar Avatar answered Sep 25 '22 00:09

meagar