capypad
0 day streak
cpp / beginner
Snippet

Return by Value: Returning Local Copies

When a function returns a pointer to dynamically allocated memory, the caller becomes responsible for freeing that memory with delete[]. This pattern is common in C++ but requires careful memory management. Modern C++ prefers returning std::vector instead.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i * 10;
}
return arr;
}
 
int main() {
int* myArray = createArray(5);
 
for (int i = 0; i < 5; i++) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
 
delete[] myArray;
 
return 0;
}
Breakdown
1
int* createArray(int size)
Function returns a pointer to dynamically allocated array
2
int* arr = new int[size];
Allocates array on the heap with new
3
return arr;
Returns the pointer, heap memory persists after function ends
4
delete[] myArray;
Must free heap memory to prevent leaks