How to do proper initialization and allocation of the composite struct?

c

Solution

If `myDataPacket` is allocated on the heap, then it will all be on the heap:

MyDataPacket *myDataPacket = malloc(sizeof(MyDataPacket));

If `myDataPacket` is an automatic variable, it will all live on the stack, including the `objectList` pointer itself, the memory it points to however, will be on the heap:

MyDataPacket myDataPacket; //this is all on the stack
myDataPacket->objectList = malloc(...) //memory allocated here is on the heap

If it's a global variable, it depends on whether or not it's initialized, and whether it's initialized to `zero` or not, but generally speaking uninitialized variables go to the `.bss` section and initialized variables go to the `data` section, and of course the dynamically allocated memory will be on the heap as usual.

If you're worried about efficiency check this SO question:

Which is faster: Stack allocation or Heap allocation

Problem

I need to create and implement usage of the struct that contains an array inside it. How to do proper initialization and allocation of the struct and array? Here's my current implementation that seems to work. However, not sure is it proper way and where is the struct allocated (on stack or on heap memory). IMHO a call to malloc makes to store an array on heap, however not sure about remaining struct members. Here are my structs: ``` typedef struct { uint8_t objectSize; double objectDepth; } ObjectData; typedef struct { ObjectData *objectList; double startMark; double endMark; } MyDataPacket; ``` Here is the function that fills and returns the struct: ``` void getMyPacket(MyDataPacket *myDataPacket, uint8_t objectNum) { myDataPacket->startMark = 10.0; myDataPacket->endMark = 60.0; myDataPacket->objectList = malloc(objectNum * sizeof(MyDataPacket)); uint8_t x; for (x = 0; x < objectNum; x++) { myDataPacket->objectList[x].objectSize = x; // just test values myDataPacket->objectList[x].objectDepth = x; // just test values } } ``` Here's function calling part: ``` uint8_t objectNum = 10; MyDataPacket myDataPacket; getMyPacket(&myDataPacket, objectNum); ``` Does the struct data is mixed and placed both on stack and heap, or everything resides at one place?

Original source

Related problems