0

This is a basic question, but I can't seem to understand how this works:

Suppose I pass a structure pointer to a function, do I need to malloc memory for this passed pointer inside the function?

e.g.,

typedef struct example_data_ {
    int serial;
    char *name;
} example_data;

int main() {

    int ret;
    example_data *ptr_ex;

    // Should I malloc memory for ptr_ex here before assigning values to it???

    ptr_ex->serial = 1;
    ptr_ex->name = 'test';

    myfunc(ptr_ex);
    return 0;
}

void myfunc(example_data *myptr) {

    //Can I directly deference the values below??? or should I malloc memory for *myptr also???

    printf("serial no: %d\n",myptr->serial); 
    printf("name: %s",myptr->name);
}

Thanks !

2
Contributors
2
Replies
5
Views
4 Years
Discussion Span
Last Post by adrawat
1

I'll answer your comments directly:

// Should I malloc memory for ptr_ex here before assigning values to it???

Yes. An unintialized pointer is not a pointer to usable memory, you must first point it to memory that you own either through dynamic allocation or through the address of an existing variable.

Though in this case you don't need a pointer. You can simply create an instance of the structure and pass its address to myfunc().

//Can I directly deference the values below???

Provided that myptr points to a valid object and the object has been initialized with non-garbage values, yes.

or should I malloc memory for *myptr also???

No. The assumption here is that the calling function owns the memory for this pointer and has set everything up properly for you to use it without worrying about managing memory.

Edited by deceptikon

Votes + Comments
excellent explaintion...
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.