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 !

Recommended Answers

All 2 Replies

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.

commented: excellent explaintion... +2

Thanks a lot for the clarification.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.