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 ..
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))).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With