Space in C++
Introduction:
"Space" in C++ usually refers to memory or storage space. As it affects how information is stored and used by a programme, memory space is a fundamental idea in programming.
Methods for manipulating memory space in C++:
- Stack Room:
Local variables and function-specific data, including return addresses, are kept in the stack, a section of memory.
In general, the stack is where variables defined inside of functions, such as pointers and integers, are kept.
The compiler automatically manages memory on the stack, and last-in, first-out (LIFO) memory allocation and deallocation are used.
Syntax:
void someFunction() {
int x = 5; // 'x' is stored on the stack
}
Example:
#include <iostream>
// Function to calculate the factorial of a number using recursion
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5; // Number for which we want to calculate the factorial
int result = factorial(num);
std::cout << "The factorial of " << num << " is: " << result << std::endl;
return 0;
}
Output:
![Space in C++](https://static.tutorialandexample.com/cpp/space-in-cpp1.png)
Explanation:
- The factorial of an integer n can be calculated using a function named factorial. As a recursive function, it one repeats itself repeatedly with decreasing n values until n reaches 0 or 1.
- We define an integer var num and set it to 5 in the main function.
- Then, given num as an argument, we invoke the factorial function, and the output is saved in the result variable.
- We then print the outcome to the console.
- Load Space
A section of memory called the heap is used in dynamic memory allocation.
The new and malloc operators in C++ are used to allocate memory to the heap. To avoid memory leaks, it is your responsibility to dispose of the memory once you have finished using it (by using delete or free).
You must be particular not to access or alter memory after it has been allocated and deallocated because the compiler does not manage heap memory automatically.
Syntax:
int* dynamicInt = new int; // Allocate an integer on the heap
*dynamicInt = 10;
delete dynamicInt; // Deallocate the memory when done
Example:
#include <iostream>
int main() {
int size = 5;
int* dynamicArray = new int[size]; // Allocate an integer array on the heap
// Initialize the array with values
for (int i = 0; i < size; ++i) {
dynamicArray[i] = i * 2;
}
// Print the array
std::cout << "Array elements: ";
for (int i = 0; i < size; ++i) {
std::cout << dynamicArray[i] << " ";
}
std::cout << std::endl;
// Deallocate the memory to prevent memory leaks
delete[] dynamicArray;
return 0;
}
Output:
![Space in C++](https://static.tutorialandexample.com/cpp/space-in-cpp2.png)
Explanation:
- In order to create an array of integers of size 5, we define an integers size and then set it to 5.
- The heap's memory is dynamically allocated for the numeric array dynamicArray using the new operator.
- The dynamicArray's elements are given some initial values (in the example, even numbers).
- We output the array's elements to the console.
- In order to avoid memory leaks, we finally dispose of the amount of memory used by dynamicArray using the delete[] operator.
- Data Storage
The memory set aside for global variables, static variables, and constants is referred to as data space.
Global variables are kept in data space and are present for the duration of the programme.
Syntax:
int globalVariable = 42; // Global variable in data space
Example:
#include <iostream>
// Global variable in data space
int globalVariable = 42;
// Constant in data space
const double PI = 3.14159265359;
int main() {
// Access and print the global variable
std::cout << "Global variable: " << globalVariable << std::endl;
// Access and print the constant
std::cout << "Constant PI: " << PI << std::endl;
return 0;
}
Output:
![Space in C++](https://static.tutorialandexample.com/cpp/space-in-cpp3.png)
Explanation:
- We specify a worldwide variable. a global variable with a global scope. The variable is present in data space and reachable from any programme function.
- In the global scope, a constant PI is declared. Additionally kept in data space, constants can be accessed at any time by the programme. Once they are defined, constants cannot be changed.
- The global variable and constant values are accessed and printed in the main function.
- Code Position
The machine code containing the program's instructions is stored in code space.
The real executable code is located here.
Syntax:
int main() {
// Program code resides in the code space
return 0;
}
Example:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
Output:
![Space in C++](https://static.tutorialandexample.com/cpp/space-in-cpp4.png)
Explanation:
- The required header file both input and output operations is included using the #include iostream> directive.
- The program's entry point is the main() function. It includes the directions for the programme.
- We employ std::cout to print "Hello, world!" to the console inside of main().
- Return 0; is used to denote a successful programme execution in the end.