user11576265
user11576265

Reputation:

Dynamically allocate an object, will the members that aren't ptrs (not dynamically allocated) in the struct be in the stack instead of the heap?

Say I have this struct:

typedef struct List_object list;
struct List_object {
    char* name;
    struct stat stats;
};

In main:

list** listObjects = malloc(sizeof(list*) * n);
    for(int i = 0; i < n; i++) {
        listObjects[i] = malloc(sizeof(list));
        listObjects[i]->name = malloc(sizeof(char) * 124);
    }

then I have a function that sets them:

void setListObjects(char* name, struct stat stats);

I was wondering if the data member struct stat stats in each object of the array listObjects will be in the heap as well?

Or will it only be listObjects and its data member name since both were allocated with malloc, and not stats?

Upvotes: 1

Views: 51

Answers (1)

Lundin
Lundin

Reputation: 214300

I was wondering if the data member struct stat stats in each object of the array listObjects will be in the heap as well?

Yes. Every struct member will be allocated on the heap. Though note that while the pointer name itself in your example will be allocated together with the struct on the heap, what it points at could be anything.

Upvotes: 1

Related Questions