C-Dynamic Memory Allocation

95 Views Asked by At
typedef struct {
    double x;
    double y;
} point;

point p1;
point* p2 = malloc(sizeof(point));

In this code where the variables p1,p2,p1.x, and p2->x are stored in stack or heap memory?

Where the mentioned variables are stored in stack or heap memory?

1

There are 1 best solutions below

3
gulpr On
typedef struct {
    double x;
    double y;
} point;

point p1;

void foo(void)
{
    point* p2 = malloc(sizeof(*p2));
    /* ... */
}
  • p1 has static storage duration (lifetime same as the whole program)
  • p2 has automatic storage duration (lifetime same as the function foo)
  • *p2 (object referenced by the pointer p2) has allocated storage duration (lifetime same as the whole program or until it is freeed)

In this code where the variables p1,p2,p1.x, and p2->x are stored in stack or heap memory?

Where the mentioned variables are stored in stack or heap memory?

C standard (language) does not say where those objects are stored (it is up to implementation) and it does not matter from the programmer's point of view. Only the storage duration is important for you (because you need to know how long the object lives). Do not focus on implementation details when you are learning.

C language doesn't know anything about stack or heap but the most popular implementations place

  • automatic storage duration objects on the stack or in processor registers. They can be also "optimized out" by the compiler and not stored at all
  • allocated storage duration objects on the heap
  • static storage duration objects in .bss or .data sections (depending if they are initialized or not). Constant ones can be stored in .rodata segment