0
#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    char* text;
    int num;
} foo;

int main(void) {

    foo* a = malloc(sizeof(foo));
    a->text = "Something";
    a->num = 4;
    printf("%s %d\n", a->text, a->num);

    foo b;
    b.text = "Something";
    b.num = 4;
    foo* c = &b;
    printf("%s %d", c->text, c->num);

    return 0;
}

Both print the exact same thing. The only difference between foo* a and foo* c is where each one points to. Which one should be preferred? I usually see malloc() more but I don't understand why.

Vasting
  • 299
  • 2
  • 10
  • It depends on the application. – cs95 Jul 05 '17 at 18:57
  • when defined from `main` it doesn't matter much because variables from `main` have a longer lifespan than any other ones in subroutines (if the data is too big, you may exhaust the stack, though) – Jean-François Fabre Jul 05 '17 at 18:58
  • 2
    Use the stack if you only intend to use the value in the scope of the function, or if you're copying the value somewhere else. Use heap if you intend to return a pointer to memory you allocated from the function, and you expect to `free()` it elsewhere after the block of memory is done being used. FWIW, heap memory takes more cycles to read and write than stack memory does, since it accesses to external RAM. – Patrick Roberts Jul 05 '17 at 18:59

2 Answers2

2

I think you should malloc() only for bigger data. You should consider that malloc() needs more time because it must find search for a data block in the heap and reserve it. If you use the struct on stack this is not necessary. So it really depends on what you are doing.

Edit: Also you should think of the scope of the variable. If the struct is needed only within the function I would prefer the stack.

Benjamin J.
  • 1,239
  • 1
  • 15
  • 28
0

Heap-allocated data is easier to share with others (i.e. across function boundaries), especially when the function that creates an object needs to have it usable when that function has exited. This is not possible with non-heap data (except when using static but that creates problems too), which can be rather limiting.

unwind
  • 391,730
  • 64
  • 469
  • 606