CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Scoping and Memory

Recall some important issues with C11 and memory allocation for identifiers:

  • Whenever we declare a new variable, such as int x, memory is allocated

  • When can this memory be freed up (so it can be used to store other variables)?

  • When the variable goes out of scope

  • When a variable goes out of scope, that memory is no longer guaranteed to store the variable's value

C++'s new operator

C++ provides another mechanism to allocate memory, which will remain allocated until manually de-allocated.

This is very similar to C11's malloc family of functions.

The new operator returns a pointer to the newly allocated memory:

#include <iostream>

    int *x = new int;

Of nore:

  • If using int x; the allocation occurs on the run-time stack,
  • If using new int; the allocation occurs within the heap.

C++'s delete operator

In a manner similar to C11's free() function, C++'s delete operator de-allocates memory that was previously allocated using new

#include <iostream>

int *x = new int;

// use memory allocated by new
....
delete x;

 


CITS2002 Systems Programming, Lecture 23, p10, 17th October 2023.