Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Memory Allocation in C

Does allocating a struct instance using malloc have any effect on the allocation of its members? Meaning that, is doing something like this:

typedef struct { int *i; } test;
int main() {
     test *t = malloc(sizeof(test));
     t->i = malloc(sizeof(int));
}

... is meaningless because i should be already on the heap, right ?

Or, the struct is just conceptual to help the programmer group two completely separate variables floating in memory? Meaning that: test *t = malloc(sizeof(test)) just allocates the memory for storing pointers to the members on the heap?

I'm quite baffled about this ..

like image 251
Amr Ayman Avatar asked Mar 19 '23 03:03

Amr Ayman


1 Answers

The i field of test is a primitive int, and mallocing test will take care of the memory needed by it. Assigning a result of malloc to i should produce a warning, as you're implicitly converting a pointer to an int.

EDIT:
As pointed out in the comments, the question has been edited since the above answer was posted. If your struct contains a pointer, mallocing the struct will allocate the memory to hold a pointer, but will not allocate the memory this pointer points to. For that, you'll need a second malloc call (e.g., test->i = malloc (sizeof (int))).

like image 193
Mureinik Avatar answered Mar 28 '23 11:03

Mureinik