These are the notes for C++ episode 10. In episode 9, pointers let a function change your variables, but the code was full of * and &. Here you will invent the reference: a second name for the same variable. Then a clean swap with pass by reference, the cannot bind non-const lvalue reference error, and const references (no copy, read-only). After that, five million board-exam marks crash the program, and you will discover the stack and the heap, ask for memory with new, give it back with delete[], and meet memory leaks, dangling pointers and the address of local variable returned warning. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
Memory addresses (like
0x7ffe4499ae44) change on every run, so yours will look different. What matters is whether two addresses are equal.
The problem: the pointer swap works, but it's noisy
Here is last episode's swap. Ravi has 65, Priya has 92, and we want to swap their marks:
#include <iostream>
#include <string>
using namespace std;
void swapMarks(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int ravi = 65, priya = 92;
swapMarks(&ravi, &priya);
cout << "Ravi: " << ravi << ", Priya: " << priya << endl;
return 0;
}
Output:
Ravi: 92, Priya: 65
It works. But look at the noise: * in the parameters, * on every use inside, and & at every call.
Why it's a problem:
- Forget one
*and you are changing an address instead of a mark. - Anyone can call it with
nullptr, and it crashes. CallingswapMarks(&ravi, nullptr);compiles fine, then prints nothing:
Segmentation fault
What we really want: hand the function the real variable, under a different name. No addresses, no stars.
The fix: a reference (Ravi is "Bittu" at home)
| In a family | In C++ | Meaning |
|---|---|---|
| Ravi, at school (his real name) | int marks = 78; |
the real variable |
| "Bittu", at home (a nickname, the SAME boy) | int& r = marks; |
a reference: another name, not a copy |
| Bittu gets a haircut, so Ravi has short hair | r = 90; → marks is 90 |
change one, both change, because there is only one |
A reference is another name for an existing variable. In int& r, the & is part of the type: int& means "reference to an int".
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks = 78;
int& r = marks;
r = 90;
cout << "marks: " << marks << endl;
cout << &marks << endl;
cout << &r << endl;
return 0;
}
Output from one run (the addresses will differ on yours, but the two lines will always match each other):
marks: 90
0x7ffe4499ae44
0x7ffe4499ae44
marks became 90 although we only wrote to r. And both addresses are exactly the same: r doesn't have a box of its own. It's a second label on the same box.
A nickname for nobody
#include <iostream>
#include <string>
using namespace std;
int main() {
int& r;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:6:10: error: 'r' declared as reference but not initialized
6 | int& r;
| ^
A reference must be tied to a variable the moment it is created, and it stays tied to that same variable forever.
The three meanings of & so far
| Where you see it | Meaning | Example |
|---|---|---|
| In front of a variable, in an expression | "address of" (episode 9) | &marks |
| After a type, in a declaration | "reference to" | int& r = marks; |
| Between two values | bitwise AND (not used in this episode) | a & b |
A clean swap: pass by reference
#include <iostream>
#include <string>
using namespace std;
void swapMarks(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int ravi = 65, priya = 92;
swapMarks(ravi, priya);
cout << "Ravi: " << ravi << ", Priya: " << priya << endl;
return 0;
}
Output:
Ravi: 92, Priya: 65
The parameters are int& a and int& b. Inside, plain a and b, no stars. The call is just swapMarks(ravi, priya), like any normal function. During the call, a is Ravi's marks and b is Priya's, so the function swaps the real marks. This is called pass by reference. (Remember the int& sneak peek in episode 7? That was this.)
Passing a plain number: "cannot bind non-const lvalue reference"
What if we pass 92 instead of priya?
#include <iostream>
#include <string>
using namespace std;
void swapMarks(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int ravi = 65, priya = 92;
swapMarks(ravi, 92);
cout << "Ravi: " << ravi << ", Priya: " << priya << endl;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:13:21: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
13 | swapMarks(ravi, 92);
| ^~
main.cpp:5:29: note: initializing argument 2 of 'void swapMarks(int&, int&)'
5 | void swapMarks(int& a, int& b) {
| ~~~~~^
In plain words:
- An lvalue is something with a box (a name and an address) that can stand on the left of
=:priya,ravi. - An rvalue is a temporary value with no box of its own:
92,ravi + 1. - Bind means "tie a reference to something".
92 is not a variable, so there is nothing for the function to change. You can't give a nickname to something that has no box.
Reference vs pointer
Reference int& r = marks; |
Pointer int* p = &marks; |
|
|---|---|---|
| Using it | like a normal variable: r = 90; |
needs *: *p = 90; |
| At the call | swapMarks(ravi, priya) |
swapMarks(&ravi, &priya) |
| Must be initialised? | Yes | No (but you should) |
| Can be null? | No | Yes, nullptr |
| Can it switch to another variable later? | No: r = other; copies other's value into marks |
Yes: p = &other; |
Rule of thumb: when a function needs to change the caller's variable, prefer a reference (int&). Use a pointer when "nothing" (nullptr) is a valid answer, or when it must point somewhere else later.
const references: an exhibit behind glass
A function prints a report card with the student's full name. How should it receive the name?
| At a museum | In C++ | What happens |
|---|---|---|
| Make a replica for each visitor? (slow and wasteful) | void printCard(string name) |
pass by value: copies the whole text on every call |
| Hand over the real statue (someone may chip it) | void printCard(string& name) |
no copy, but the function can change it |
| The real statue, behind glass: look, don't touch | void printCard(const string& name) |
const reference: no copy, read-only |
Here is the "real statue" danger. With a plain string&, a careless function damages the caller's string:
#include <iostream>
#include <string>
using namespace std;
void printCard(string& name) {
name[0] = 'X';
cout << "Report card: " << name << endl;
}
int main() {
string student = "Meenakshi Raghunathan";
printCard(student);
cout << "In main: " << student << endl;
return 0;
}
Output:
Report card: Xeenakshi Raghunathan
In main: Xeenakshi Raghunathan
Now put the statue behind glass with const, and make the same mistake:
#include <iostream>
#include <string>
using namespace std;
void printCard(const string& name) {
name[0] = 'X';
cout << "Report card: " << name << endl;
}
int main() {
string student = "Meenakshi Raghunathan";
printCard(student);
return 0;
}
main.cpp: In function 'void printCard(const std::string&)':
main.cpp:6:13: error: assignment of read-only location '(& name)->std::__cxx11::basic_string<char>::operator[](0)'
6 | name[0] = 'X';
The glass did its job: a const reference can be read, never changed. (The long text in quotes is just g++'s internal way of writing name[0].) Remove that line:
#include <iostream>
#include <string>
using namespace std;
void printCard(const string& name) {
cout << "Report card: " << name << endl;
}
int main() {
string student = "Meenakshi Raghunathan";
printCard(student);
return 0;
}
Output:
Report card: Meenakshi Raghunathan
No copy was made, and the name is safe.
- Big things you only read (
string, arrays of data, later structs and vectors):const T&. - Small things like
int,double,char: a plain copy is fine (and just as fast). - Things the function must change:
T&withoutconst.
Bonus: a const reference can bind to a temporary, because it promises not to change it. This compiles and runs:
#include <iostream>
using namespace std;
void show(const int& m) {
cout << m << endl;
}
int main() {
show(92);
const int& r = 78;
cout << r << endl;
return 0;
}
Output:
92
78
The next problem: five million board-exam marks
Forget one class. The exam board needs to store the marks of every student in the state: 5,000,000 of them. The obvious attempt is an ordinary local array:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int N = 5000000;
int marks[N];
for (int i = 0; i < N; i++) {
marks[i] = i % 101;
}
cout << "Stored " << N << " marks" << endl;
cout << "Last: " << marks[N - 1] << endl;
return 0;
}
It compiles without a single warning. Then:
Segmentation fault
Not even Stored was printed. But 5,000,000 ints × 4 bytes is only 20 MB, and the computer has gigabytes. So why?
Why it fails: the stack is a small study desk
| At the office | In memory | Details |
|---|---|---|
| Your study desk: handy, cleared when you leave, but small | The stack | local variables live here; about 8 MB on this machine |
| A rented godown: huge, but you must ask for space | The heap (ask with new) |
gigabytes; you ask for it while the program runs |
| Return the key when done, or pay rent forever | delete / delete[] |
you must give the memory back; C++ won't do it for you |
- Local variables (including local arrays) live on the stack. It is fast and automatic: when a function ends, its locals are cleared away. But it is small. On this machine the limit is about 8 MB (typical for Linux, but it differs between systems and settings).
- Our 20 MB array fell off the desk. Using more stack than you have is called a stack overflow, and here it shows up as a
Segmentation fault: the program touched memory it is not allowed to touch, so the operating system stopped it. - The heap (also called the free store) is the big memory pool. You ask for a piece with
new, and you give it back withdelete.
The fix: new int[N] on the heap
Change one line: int* marks = new int[N];.
#include <iostream>
#include <string>
using namespace std;
int main() {
const int N = 5000000;
int* marks = new int[N];
for (int i = 0; i < N; i++) {
marks[i] = i % 101;
}
cout << "Stored " << N << " marks" << endl;
cout << "Last: " << marks[N - 1] << endl;
delete[] marks;
return 0;
}
Output:
Stored 5000000 marks
Last: 95
(4999999 % 101 is 95.) Twenty megabytes, no crash.
new int[N]finds space for N ints on the heap and gives back the address of the first one. Somarksis a pointer (int*).marks[i]still works, because square brackets work on pointers too (episode 9).delete[] marks;gives the godown back.
You just invented dynamic memory: memory you ask for while the program runs.
Memory that outlives a function: notes on a cleared desk
A function makeMarks builds an array and returns it to main. But the array is a local, built on the function's desk. When the function ends, the desk is cleared:
#include <iostream>
#include <string>
using namespace std;
int* makeMarks() {
int m[3] = {78, 92, 65};
return m;
}
int main() {
int* p = makeMarks();
cout << p[0] << endl;
return 0;
}
main.cpp: In function 'int* makeMarks()':
main.cpp:7:12: warning: address of local variable 'm' returned [-Wreturn-local-addr]
7 | return m;
| ^
main.cpp:6:9: note: declared here
6 | int m[3] = {78, 92, 65};
| ^
Segmentation fault
This is a warning, not an error, so the program was still built and run, and then it crashed. g++ warned us, and it was right: main received the address of something that no longer exists. (Reading it is undefined behaviour: on another compiler or setting it might print garbage, or even 78 by luck. Never rely on it.)
The fix: build it in the godown. Heap memory stays until someone deletes it, so it survives the function:
#include <iostream>
#include <string>
using namespace std;
int* makeMarks() {
int* m = new int[3]{78, 92, 65};
return m;
}
int main() {
int* p = makeMarks();
cout << p[0] << endl;
delete[] p;
p = nullptr;
return 0;
}
Output:
78
new int[3]{78, 92, 65} makes a heap array with those starting values. Now main owns that memory: it prints, deletes it, and sets p to nullptr.
Rules for new and delete
| You create with | You free with | Example |
|---|---|---|
new int(78) (one int, value in round brackets) |
delete p; |
int* p = new int(78); |
new int[n] (an array, size in square brackets) |
delete[] a; |
int* a = new int[n]; |
- Every
newneeds exactly onedelete. Arrays needdelete[]. - Forget the delete → memory leak. The memory stays taken until the program ends, like paying rent on a godown you forgot about. A short program won't notice, but a server that runs for weeks keeps leaking until it runs out of memory. There is no error message: leaks are silent.
- Use after delete → dangling pointer. The pointer still holds the old address, like a key to a godown that is now someone else's.
- After
delete, set the pointer tonullptr.deleteon anullptrdoes nothing, so it is safe.
A single heap int, used and cleaned up properly:
#include <iostream>
using namespace std;
int main() {
int* p = new int(78);
cout << "Value: " << *p << endl;
*p = *p + 5;
cout << "After grace: " << *p << endl;
delete p;
p = nullptr;
if (p == nullptr) {
cout << "p is empty now" << endl;
}
delete p;
cout << "delete on nullptr is safe" << endl;
return 0;
}
Output:
Value: 78
After grace: 83
p is empty now
delete on nullptr is safe
Here is a dangling pointer in action, reading after delete:
#include <iostream>
using namespace std;
int main() {
int* p = new int(78);
delete p;
cout << *p << endl;
return 0;
}
No error, no warning, no crash, just a wrong number. Three runs printed:
1593261673
1680061471
1584796449
That is undefined behaviour: garbage that changes every run. If you had set p = nullptr; after delete, the same cout << *p gives a clear Segmentation fault instead of a silent wrong answer. A loud bug is easier to find than a quiet one.
Later in the course, vector and smart pointers will do this cleanup for you. For now, pair every new with its delete.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
| Reference with nothing to refer to | int& r; |
error: 'r' declared as reference but not initialized |
int& r = marks; |
Passing a value to an int& parameter |
swapMarks(ravi, 92); |
error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int' |
pass a variable |
| Tying a plain reference to a number | int& r = 78; |
error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int' |
const int& r = 78; or use a variable |
Changing something through a const reference |
name[0] = 'X'; with const string& name |
error: assignment of read-only location '(& name)->std::__cxx11::basic_string<char>::operator[](0)' |
don't change it, or drop const |
| Huge local array | int marks[5000000]; inside main |
compiles; at run time Segmentation fault (stack overflow) |
new int[N] ... delete[] |
| Returning the address of a local | int m[3]; return m; |
warning: address of local variable 'm' returned [-Wreturn-local-addr], then Segmentation fault |
return heap memory (new) |
| Returning a reference to a local | int& bestMark() { int best = 92; return best; } |
warning: reference to local variable 'best' returned [-Wreturn-local-addr], then Segmentation fault |
return by value: int bestMark() |
Storing new's result in an int |
int marks = new int[5]; |
error: invalid conversion from 'int*' to 'int' [-fpermissive] |
int* marks = new int[5]; |
delete instead of delete[] for an array |
int* marks = new int[5]; ... delete marks; |
no message with our command; ran and printed 78. Undefined behaviour. With -Wall: warning: 'void operator delete(void*, std::size_t)' called on pointer returned from a mismatched allocation function [-Wmismatched-new-delete] |
delete[] marks; |
delete on a stack variable |
int marks = 78; int* p = &marks; delete p; |
warning: 'void operator delete(void*, std::size_t)' called on unallocated object 'marks' [-Wfree-nonheap-object], then at run time munmap_chunk(): invalid pointer and Aborted |
only delete what came from new |
Using memory after delete |
delete p; cout << *p; |
no message; printed a different garbage number on each run | set p = nullptr; after delete and don't use it |
Forgetting delete |
new int[n] with no delete[] |
no message at all: a silent memory leak | one delete[] for every new[] |
Mini project: as many students as the user types
Rao ma'am's school has classes of different sizes, and we only learn the size when the program runs. A normal array needs its size fixed in the code, but new int[n] can use a size typed by the user.
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cout << "How many students? ";
cin >> n;
int* marks = new int[n];
int total = 0;
for (int i = 0; i < n; i++) {
cin >> marks[i];
total = total + marks[i];
}
cout << endl << "Average of " << n << ": " << total / double(n) << endl;
delete[] marks;
marks = nullptr;
return 0;
}
Input:
5
78 92 65 88 71
Output:
How many students?
Average of 5: 78.8
Now a class of 8, same program, no changes. Input:
8
78 92 65 88 71 59 95 84
Output:
How many students?
Average of 8: 79
- 78 + 92 + 65 + 88 + 71 = 394, and 394 / 5 = 78.8. Adding 59 + 95 + 84 gives 632, and 632 / 8 = 79.
total / double(n)turnsninto adoubleso the division keeps the decimal part.- The input is not echoed in the output, because it comes from stdin, not from
cout. That is why "How many students?" stands alone on its line. - The array is exactly as big as the class, chosen while the program runs.
- Try it: also print the highest mark.
Practice
- Write
void addGrace(int& marks, int g = 5)and test it. - Write
void printAll(const string& title, ...)that prints a title and a list of names. - Read
n, makenew double[n]prices, print the total, and delete it. - Predict: what happens if you
delete[]the same pointer twice?
Solution
1. int& lets the function change the caller's variable; the default argument (episode 7) gives 5 grace marks unless told otherwise. Output: Ravi: 83 and Priya: 33.
#include <iostream>
using namespace std;
void addGrace(int& marks, int g = 5) {
marks = marks + g;
}
int main() {
int ravi = 78, priya = 30;
addGrace(ravi);
addGrace(priya, 3);
cout << "Ravi: " << ravi << endl;
cout << "Priya: " << priya << endl;
return 0;
}
2. The title is a const string& (read only, no copy). The list is an array of strings plus its size; the array parameter is also marked const because printAll only reads it.
#include <iostream>
#include <string>
using namespace std;
void printAll(const string& title, const string names[], int n) {
cout << "== " << title << " ==" << endl;
for (int i = 0; i < n; i++) {
cout << i + 1 << ". " << names[i] << endl;
}
}
int main() {
string toppers[3] = {"Meenakshi", "Arjun", "Priya"};
printAll("Class 10 toppers", toppers, 3);
return 0;
}
Output:
== Class 10 toppers ==
1. Meenakshi
2. Arjun
3. Priya
3. The same shape as the mini project, with double.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "How many items? ";
cin >> n;
double* prices = new double[n];
double total = 0;
for (int i = 0; i < n; i++) {
cin >> prices[i];
total = total + prices[i];
}
cout << endl << "Total: Rs " << total << endl;
delete[] prices;
prices = nullptr;
return 0;
}
Input:
4
45.5 120 60 30.25
Output:
How many items?
Total: Rs 255.75
4. Deleting the same memory twice is called a double free, and it is undefined behaviour: C++ makes no promise about what happens. Here is the test:
#include <iostream>
using namespace std;
int main() {
int* marks = new int[3]{78, 92, 65};
cout << "First: " << marks[0] << endl;
delete[] marks;
delete[] marks;
cout << "After two deletes" << endl;
return 0;
}
What really happened with g++ -O2 -std=c++17 main.cpp -o main: no error, no warning, and three runs all printed
First: 78
After two deletes
with no crash. That does not mean it is safe. With -O2, the optimiser saw that this tiny array is only read once and removed the heap allocation (and both deletes) completely, so there was nothing left to free twice. Built without optimisation (g++ -O0 -std=c++17 main.cpp -o main, a different command), the same code crashed:
First: 78
free(): double free detected in tcache 2
Aborted
So the honest answer is: it might crash, it might seem fine, it might corrupt memory and fail much later. That is exactly what undefined behaviour means. The cure is the nullptr rule: after delete[] marks; marks = nullptr;, a second delete[] marks; does nothing, and the program prints First: 78 and After two deletes safely (verified).
Quick quiz
What does this print?
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 5;
int& r = a;
int b = 20;
r = b;
b = 99;
cout << a << endl;
return 0;
}
- A.
5 - B.
20 - C.
99 - D. Compile error
Answer
B: 20 (verified). r is another name for a. A reference can't be moved, so r = b; copies b's value (20) into a; it does not make r refer to b. Changing b to 99 afterwards doesn't touch a.
Interview questions
- What is a reference in C++? Another name (an alias) for an existing variable. It has the same address as the original, and anything done through it happens to the original.
- What are the differences between a reference and a pointer? A reference must be initialised, can't be null, can't be re-pointed to another variable, and is used without
*. A pointer can benullptr, can change what it points to, and needs*to reach the value. - What is pass by reference, and when do you use it? The parameter is a reference (
int& a), so the function works on the caller's variable. Use it when the function must change the caller's variable, orconst T&to avoid copying big objects. - Why use
const string&instead ofstringas a parameter? Passing by value copies the whole string on every call. A const reference avoids the copy and still guarantees the function can't modify it. It can also bind to temporaries like"Meena". - What are lvalues and rvalues? An lvalue has an identity (a name and address) and can appear on the left of
=, like a variable. An rvalue is a temporary value like92ora + b. A non-constT&can bind only to lvalues; aconst T&can bind to both. - What is the difference between the stack and the heap? The stack holds local variables; it is small (often a few MB) and managed automatically when functions start and end. The heap is large and managed by you with
newanddelete; its memory lives until you delete it. - What is a memory leak? Heap memory that is never freed, usually because the program lost or forgot the pointer. It stays taken until the program ends; in long-running programs it keeps growing.
- What is a dangling pointer? A pointer that still holds the address of memory that has been freed (or of a local that has gone out of scope). Using it is undefined behaviour. Setting the pointer to
nullptrafterdeletehelps. - What is the difference between
deleteanddelete[]?deletefrees a single object fromnew T;delete[]frees an array fromnew T[n]. Mixing them up is undefined behaviour. - Why is returning the address of a local variable wrong? The local is destroyed when the function returns, so the caller receives a dangling address. Return by value, or return heap memory (later: a
vectoror smart pointer).
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Reference | Another name for an existing variable; not a copy | int& r = marks; |
| Alias | Another word for a second name, like a nickname | r is an alias of marks |
& in a type |
"reference to" | int& |
& before a variable |
"address of" | &marks |
| Address | The location of a variable's box in memory; printed in hex and different on every run | 0x7ffe4499ae44 |
| Pointer | A variable that stores an address | int* p = &marks; |
Dereference (*) |
Go to the address a pointer holds and use the value there | *p = 90; |
nullptr |
A pointer value meaning "points to nothing" | p = nullptr; |
| Initialise | Give a variable (or reference) its first value when it is created | int& r = marks; |
| Bind | Tie a reference to a particular variable or value | r is bound to marks |
| Pass by value | The function gets a copy; the caller's variable can't change | void printCard(string name) |
| Pass by reference | The function gets the caller's real variable under a new name | void swapMarks(int& a, int& b) |
const |
"Can't be changed" | const int N = 5000000; |
| const reference | A reference that can read but not change; no copy is made | const string& name |
| Read-only | You can look at it but not write to it | changing name[0] through const string& is an error |
| lvalue | Something with a box and a name that can stand on the left of = |
ravi, marks[2] |
| rvalue | A temporary value with no box of its own | 92, ravi + 1 |
| Temporary | A value that exists only for a moment during an expression | the 92 in swapMarks(ravi, 92) |
| Local variable | A variable inside a function; destroyed when the function ends | int m[3] in makeMarks |
| Stack | The small, automatic memory where local variables live (about 8 MB on this machine) | int marks[N]; inside main |
| Heap (free store) | The large memory pool you ask for while the program runs | new int[N] |
| Stack overflow | Using more stack memory than there is, which crashes the program | a 20 MB local array |
| Segmentation fault | A crash: the program touched memory it isn't allowed to, so the OS stopped it | the 5-million-marks array |
| Dynamic memory | Memory requested while the program runs, of a size you may only know then | new int[n] |
new |
Asks for heap memory and returns its address | int* p = new int(78); |
new[] |
Asks for a heap array | int* a = new int[n]; |
delete |
Gives back memory from new |
delete p; |
delete[] |
Gives back an array from new[] |
delete[] a; |
| Memory leak | Heap memory that is never given back | new int[n] with no delete[] |
| Dangling pointer | A pointer to memory that no longer belongs to you | p after delete p; |
| Double free | Deleting the same memory twice; undefined behaviour | delete[] marks; twice |
| Undefined behaviour | Code whose result C++ doesn't define: it may work, print garbage or crash | reading *p after delete p |
| Warning | g++ thinks something is wrong but still builds the program | address of local variable 'm' returned |
| Compile error | A mistake g++ finds before running; no program is produced | 'r' declared as reference but not initialized |
| Aborted | The program stopped itself after detecting a serious memory problem | free(): double free detected in tcache 2 |
Optimiser (-O2) |
The part of g++ that rewrites your code to run faster, without changing what correct code does | it removed the unused heap array in homework 4 |
| Ownership | Being the part of the code responsible for deleting some memory | main owns the array returned by makeMarks |
Summary
- The pointer swap works but is noisy (
*,&) and can be handednullptr. A reference (int& r = x;) is another name for the same variable: same address, one box. - A reference must be initialised (
declared as reference but not initialized), can't be null, and never moves:r = other;copies the value. int¶meters give pass by reference: a cleanswapMarks(ravi, priya). A plain number can't bind toint&(cannot bind non-const lvalue reference ... to an rvalue).const T&: no copy, read-only (assignment of read-only location). Use it for big things you only read.- Local variables live on the stack: small (about 8 MB on this machine) and automatic. A 20 MB local array caused a stack overflow:
Segmentation fault. - The heap is big and manual:
new/delete,new[]/delete[]. Everynewneeds exactly onedelete. - Forgetting
deleteis a memory leak; using memory afterdeleteis a dangling pointer. Set pointers tonullptrafterdelete. - Never return the address of a local variable; return heap memory (or a value) instead.
Next episode: structs. Today our report card needed a names array, a marks array, and maybe a roll number array, all kept in step by hand. What if one student's data could travel together? Next time, you'll invent structs: a student's name, roll number and marks kept together.