Dhemmlerf
Dhemmlerf

Reputation: 33

Does dynamic allocation store anything in heap? - C Language

Here and there people seem to agree that a dynamically allocated pointer or struct, is stored in the heap as well as the variables it is pointing to.

typedef struct {
  char** data;
  int size;
}a_struct;

void aFunction() {
  int* p = (int*) calloc(rows, sizeof(int));
  printf("p:   %11d\n", &p);
  printf("p_0: %11d\n", &p[0]);
  printf("p_1: %11d\n", &p[1]);

  int a = 2;
  printf("a:   %11d\n", &a);

  int* p_a = &a;
  printf("p_a: %11d\n", &p_a);

  int b = 3;
  printf("b:   %11d\n", &b);

  a_struct* s = (a_struct*) malloc(sizeof(a_struct));
  printf("s:   %11d\n", &s);
}
Output:
p:    1741256048     
p_0:  1426420384
p_1:  1426420388
a:    1741256040
p_a:  1741256056
b:    1741256044
s:    1741256064

Nevertheless when aFunction is called, it seems that actually only the variables pointed to by a pointer are stored in heap, and the pointer itself is stored in stack. I've tested this on different machines. ¿Am I right or what I'm missing?

Upvotes: 0

Views: 63

Answers (1)

jpa
jpa

Reputation: 12176

Here and there people seem to agree that a dynamically allocated pointer or struct, is stored in the heap as well as the variables it is pointing to.

This allocates a stack-allocated pointer, which you use to store the address of a dynamically allocated int array:

int* p = (int*) calloc(rows, sizeof(int));

If you wanted to make a dynamically allocated pointer, you'd instead write:

int** pp = (int**) calloc(1, sizeof(int*));

Note that we still store the address of the dynamically allocated pointer in a stack allocated pointer. If we didn't, we'd just lose access to the dynamic allocation. You can use that dynamically allocated pointer to store the address of dynamically allocated array, like before:

*pp = (int*) calloc(rows, sizeof(int));

To release memory, you'd have to free both the array and the pointer:

free(*pp);
free(pp);

Upvotes: 3

Related Questions