Swap values: Stack and Heap memories

Ansif Blog
2 min readFeb 6, 2024

--

Method 1: The below code operates solely on the stack memory. Variables a and b are allocated on the stack, and their values are directly swapped. No dynamic memory allocation is involved.

#include <iostream>
using namespace std;
int main()
{
int a = 100;
int b = 200;

cout << "Before swapping " << a << " " << b <<"\n";

int temp = a;
a = b;
b = temp;

cout << "After swapping " << a << " " << b;
return 0;
}

Output:
Before swapping 100 200
After swapping 200 100

Method 2: In the below code, variables x and y are stack-allocated, and their addresses are stored in pointers a and b. The pointers are then swapped, indirectly affecting values on the stack.

using namespace std;
int main()
{
int x = 100;
int y = 200;

int *a = &x;
int *b = &y;

cout << "Before swapping " << *a << " " << *b <<"\n";

int *temp = a;
a = b;
b = temp;

cout << "After swapping " << *a << " " << *b;
return 0;
}

Output:
Before swapping 100 200
After swapping 200 100

Method 3: The below code involves dynamic memory allocation on the heap. Pointers a and b are used to allocate memory for integers. After swapping the pointers, the allocated memory is freed to prevent memory leaks. The code combines stack and heap memory usage


#include <iostream>
using namespace std;
int main()
{
int *a = new int;
int *b = new int;

*a = 100;
*b = 200;

cout << "Before swapping " << *a << " " << *b <<"\n";

int *temp = a;
a = b;
b = temp;

cout << "After swapping " << *a << " " << *b;

delete a; // Delete the memory originally pointed to by a
delete b; // Delete the memory originally pointed to by b
return 0;
}

Output:
Before swapping 100 200
After swapping 200 100

Other Types of Pointers

Nullptr (nullptr): Introduced in C++ 11, nullptr is a keyword representing a null pointer used instead of NULL or 0

int* ptr = nullptr;

uniquePtr represents exclusive ownership of a dynamically allocated object, pointing to a specific memory address.

#include <memory>
std::unique_ptr<int> uniquePtr = std::make_unique<int>(42);

shared_ptr share ownership based on reference count

#include <memory>
std::shared_ptr<int> sharedPtr1 = std::make_shared<int>(42);
std::shared_ptr<int> sharedPtr2 = sharedPtr1; //

std::weak_ptr<T>: Similar to std::shared_ptr, but it doesn’t affect the reference count

--

--