DEV Community

David Hwang
David Hwang

Posted on

5/25 TIL: C++ basics (heap memory, referencing, pointer to struct)

Heap Memory in C

  • The heap is a large pool of memory that can be used dynamically - it is also known as the 'free store'. This is memory that is not automatically managed and you have to explicitly allocate & deallocate. It is where global variables are stored and you have whats called 'memory leak' if you fail to free/deallocate the memory.
  • To assign memory in heap, we use malloc()
  • You must delete (release/de-allocate) the memory in whenever you are dynamically allocating memory Ex) free(p) in C and delete [] p in C++ where p is an array

// allocates 20 bytes (5 * 4) of heap memory holding an int and assign that pointer to p

p = (int *)malloc(5 * sizeof(int));

free(p);

// C++

p = new int[5];

delete [] p;

Enter fullscreen mode Exit fullscreen mode
  • Every pointer takes 8 bytes of memory regardless of its data type

Referencing in C++ (only C++)

  • Nickname/alias given to a variable

int a = 10;

int &r = a;

Enter fullscreen mode Exit fullscreen mode
  • Reference has to be initialized (it cannot just be declared)
  • Now the variable a is also "called" r (this is not related to pointer)
  • Useful in parameter passing

Ex)


// instead of having to pass pointers 

void swap(int *x, int *y) { ... }

int main() {

int a = 10; b = 20;

swap(&a, &b);

}

// we can use referencing; now we don't have to pass the pointers

void swap(int &x, int &y) { ... }

int main() {

int a = 10; b = 20;

swap(a, b);

}

Enter fullscreen mode Exit fullscreen mode

Pointer to Struct


struct userInfo u={'david', 25};

struct userInfo *p = &u;

// this won't work bc the dot takes precedence

*p.name = 'davidd';

// instead wrap p inside brackets

(*p).name = 'davidd';

// OR

p → name = 'davidd';

Enter fullscreen mode Exit fullscreen mode

Create an object dynamically in heap using pointer


// malloc returns a void pointer; so we typecast it 

p = (struct userInfo*) malloc(sizeof(struct userInfo));

Enter fullscreen mode Exit fullscreen mode

Array as Parameter

  • Arrays can only be passed by address; it cannot be passed by value at all (both C & C++)

// when we receive an array with square brackets, it can only be a pointer to the array 

void funcOne(int A[]) { ... }

// for this we have a pointer to an integer; it can point to any integer and even the array

void funcOne(int *A) { ... }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)