4

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?

4

3 回答 3

4

如果myDataPacket是在堆上分配的,那么它将全部在堆上:

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

如果myDataPacket是一个自动变量,它将全部存在于堆栈中,包括objectList指针本身,它指向的内存,但是,将在堆上:

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

如果是全局变量zero,就是否初始化了,是否.bss初始化data为像往常一样堆。

如果您担心效率,请检查这个 SO 问题:

哪个更快:堆栈分配或堆分配

于 2012-11-12T13:34:17.963 回答
2

回答你的问题:如果myDataPacket是函数内部的局部变量,那么它将被放置在堆栈上,而myDataPacket.objectList将被放置在堆上(并且也需要被释放)。

于 2012-11-12T13:27:59.100 回答
1

改变

myDataPacket->objectList = malloc(objectNum * sizeof(MyDataPacket));

myDataPacket->objectList = malloc(objectNum * sizeof(ObjectData));

那应该可以解决您的问题。您当前正在分配一些 MyDataPackets 而不是 ObjectData。

于 2012-11-12T14:11:04.943 回答