开发者

What is the best way to allocate memory to variables within a structure?

For example, I have this structure and code:

typedef struct
{
long long *number;
} test;

test * test_structure;
test_structure = malloc(sizeof(test));
test_structure->number = malloc(sizeof(long long) * 100);
free(test_structure->number);
free(test_structure);

versus this structure and code:

typed开发者_StackOverflowef struct
{
long long number[100];
} test;

test * test_structure;
test_structure = malloc(sizeof(test));
free(test_structure);

Since i know that the number array will ALWAYS be 100, are either of these methods perfectly acceptable, or is one way better than the other, and why?


The second way is better for several reasons:

  1. You only have to release one allocation, not two (reduced chance of memory leakage).
  2. You have encoded the size of the array in the data structure, and this could help with code analysis. The first version could have any size, and no-one can say that any subscript is wrong. If you added a 'size' member that was appropriately initialized to the first structure, there would be less force to this argument, but not very much less force.
  3. You can copy the entire second structure with a structure assignment; you can't copy the first structure in the same way.
  4. The assembler generated is slightly different (longer) for the first (it has to fetch the address from the member, then dereference it, instead of just dereferencing with the second).

With all that said, the two methods are substantially the same. You use (I was tempted to say 'waste' but that's not quite fair) more space with the first, but it is unlikely to be a major problem (and if it was, you'd be likely to want to vary the size from 100, as that will save you more space than tinkering with pointer vs array).


I would definitely go for the latter. The memory profile will be almost identical. With just one memory allocation, and therefore fewer moving parts to keep track of, there's practically no reason to consider the former alternative.

In fact, even for an array of unknown length, I would probably go for an naked long long * rather than a struct wrapper that seems adds no value.


I go with the latter ONLY because you say you know the size of the array. If not, then the former.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜