Home > Enterprise >  Is my data stored in heap or in stack in below code
Is my data stored in heap or in stack in below code

Time:03-11

In the below code, I get memory through malloc and pointed it by pointer ptr. When I assigned value as shown I stored the data in pointer and we know that pointer is located in stack frame.

So my question is: My data(integers) is stored in stack or in heap?

#include<stdio.h>
#include<stdlib.h>
void main()
{
  int *ptr;
  ptr=(int*)malloc(5*sizeof(int));
  ptr[0]=5;
  ptr[1]=6;
  ptr[2]=8;
  ptr[3]=10;
  ptr[4]=11;
}

CodePudding user response:

Yes, the pointer is stored on the stack, but the memory it points to is on the heap. Therefore, the integers are stored on the heap.

CodePudding user response:

Pedantically speaking, from the perspective of the C standard, all the objects involved here simply occupy some memory that is suitably aligned, and disjointed from other objects.

While the notion of a stack and heap are commonplace, the C standard makes no reference to either terms. How and where data is stored is mostly implementation-defined.

The principle thing differentiating them is their visibility and effective lifetimes (see: Storage duration, Lifetime, and Scope):

  • The use of ptr is valid until main returns.

  • The use of the memory at the address returned by malloc is valid until it is deallocated.


Practically speaking, however, it is generally fair to refer to objects with

  • automatic storage duration as existing on the "stack",
  • static storage duration as existing in the "data segment", and
  • allocated storage duration as existing on the "heap",

as this a very common way C implementations work.

With this terminology, the object designated by the identifier ptr exists on the stack, and the objects accessed via the pointer returned by malloc exist on the heap.

  • Related