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


for example, have structure , 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 structure , code:

typedef struct { long long number[100]; } test;  test * test_structure; test_structure = malloc(sizeof(test)); free(test_structure); 

since know number array 100, either of these methods acceptable, or 1 way better other, , why?

the second way better several reasons:

  1. you have release 1 allocation, not 2 (reduced chance of memory leakage).
  2. you have encoded size of array in data structure, , code analysis. first version have size, , no-one can subscript wrong. if added 'size' member appropriately initialized first structure, there less force argument, not less force.
  3. you can copy entire second structure structure assignment; can't copy first structure in same way.
  4. the assembler generated different (longer) first (it has fetch address member, dereference it, instead of dereferencing second).

with said, 2 methods substantially same. use (i tempted 'waste' that's not quite fair) more space first, unlikely major problem (and if was, you'd want vary size 100, save more space tinkering pointer vs array).


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -