CS253 Dynamic Memory Allocation
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.
In C++, we use keywords to allocate & free memory:
new
delete
new []
delete []
You have to delete the memory that you allocate.
Don’t delete it more than once!
int *p = new int; *p = 42; cout << p << ' ' << *p << '\n'; delete p;
0x25602b0 42
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,
new
with delete
, and new []
with delete []
new
, you must call delete
.
new []
, you must call delete []
.
If you mix them up, the system might catch your error, or it might not.
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.
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.
Modified: 2017-01-30T14:48 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |