CS253: Software Development with C++

Spring 2018

Dynamic Memory Allocation

See this page as a slide show

CS253 Dynamic Memory Allocation

The old C way

In C, we used functions to allocate & free memory:

They still work, but don’t use them. They’re not type-safe, and they don’t call ctors & dtors (constructors and destructors).

The new C++ way

In C++, we use keywords to allocate & free memory:

You have to delete the memory that you allocate.

Don’t delete it more than once!

Scalar Example

int *p = new int;
*p = 42;
cout << p << ' ' << *p << '\n';
delete p;
0x16492b0 42

Array Example

int *a = new int[10];
for (int i=0; i<10; i++)
    a[i] = i*11;

for (int i=0; i<10; i++)
    cout << a[i] << ",";

delete[] a;         // Note the []
0,11,22,33,44,55,66,77,88,99,

Match new with delete, and new [] with delete []

If you mix them up, the system might catch your error, or it might not.

Java Error

Java programmers, remember that objects do not have to be dynamically allocated. You can, but you don’t have to.

string s = new string;
c.cc:1: error: conversion from 'std::__cxx11::string*' {aka 
   'std::__cxx11::basic_string<char>*'} to non-scalar type 
   'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} requested

Instead, just declare the string:

string s = "Hi there\n";
cout << s;
Hi there

Sure, the string allocates dynamic memory, internally, but that’s none of your business.

Avoid all of this

In general, use standard containers such as string, vector, or list when you can. They handle the dynamic memory allocation, so you don’t have to.

If that’s not possible, then consider unique_ptr and shared_ptr.

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:51

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building