4

I have the following script:

typedef struct {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
} color;

color c1;
color* c2 = malloc(sizeof(color));

I would like to know where c1 and c2 are stored. I know malloc stores on the heap, but c2 is a pointer and those get stored on the stack? And is c1 stored on either the heap or the stack?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54

1 Answers1

12

C standard does not define or even refer to the term "stack". A stack is an implementation concept, even if most (if not all commonly used) compilers make use of this concept. And it is subject to the compiler to decide when or what is put on the stack or not.

Most times, variables with automatic storage duration (e.g. local variables as in your case) get pushed on the stack, whereas dynamically allocated memory is drawn from the heap.

So c1 is probably on the stack, pointer c2 is on the stack, too, but the object to which it points is on the heap.

Hope it helps somehow.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58