> For the complete documentation index, see [llms.txt](https://nodejsdocs.gitbook.io/everthing-c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nodejsdocs.gitbook.io/everthing-c++/arrays-strings-pointers-and-memory-allocation.md).

# Arrays, Strings, Pointers & Memory Allocation

This chapter builds a strong foundation for understanding memory layout and access in C++. We'll connect everyday coding structures (arrays, strings, and pointers) to their underlying performance implications — key for writing high-performance systems.

***

### 1. Arrays

#### 1.1 Static Arrays (Stack)

```cpp
int arr[5] = {1, 2, 3, 4, 5};
```

* Memory is allocated on the **stack**.
* Size is fixed at compile-time.
* Fast access due to **contiguous memory layout**.

**Beginner Tip:**

Array indexing is zero-based: `arr[0]` refers to the first element.

**Medium-Level Notes:**

* Out-of-bound access leads to **undefined behavior**.
* Use `std::array<T, N>` for safer type-checked access in C++.

***

#### 1.2 Dynamic Arrays (Heap)

```cpp
int* arr = new int[5];
// Don't forget to delete!
delete[] arr;
```

* Allocated on **heap**, lifetime controlled manually.
* `new[]` returns pointer to first element.

**Best Practices:**

* Always `delete[]` what you `new[]`.
* Prefer `std::vector` for dynamic arrays with RAII.

**Advanced Trick:**

Use custom allocators with `std::vector` to improve cache alignment.

***

### 2. Strings

#### 2.1 C-Style Strings

```cpp
char str[] = "hello";
```

* Null-terminated (`\0`) array of chars.
* Dangerous if not managed carefully (buffer overflows).

**Use-case:**

* Interfacing with C libraries or embedded systems.

#### 2.2 `std::string`

```cpp
std::string s = "hello";
```

* Manages memory automatically.
* Supports copy, move, and slicing.

#### 2.3 Small String Optimization (SSO)

Many implementations store short strings (≤15 chars) **on the stack** to avoid heap allocations.

```cpp
std::string short_str = "abc"; // stack allocated in many libs
```

**Performance Tip:**

Avoid repeated `+=` or `append()` in loops; it may cause frequent reallocations.

***

### 3. Pointers

#### 3.1 Basics

```cpp
int x = 10;
int* p = &x;
```

* `*p` dereferences to get the value.
* `&x` gets the address of x.

**Beginner Tip:**

`*` has two meanings:

* Declaration: `int* p;` → pointer to int
* Usage: `*p` → dereference pointer

#### 3.2 Pointer Arithmetic

```cpp
int arr[] = {1, 2, 3};
int* p = arr;
std::cout << *(p + 1); // prints 2
```

* Valid only within same array bounds.
* Dangerous across unrelated memory.

#### 3.3 `const` with pointers

```cpp
const int* p1 = &x; // can't modify *p1
int* const p2 = &x; // p2 can't point elsewhere
const int* const p3 = &x; // neither *p3 nor p3 modifiable
```

#### 3.4 Pointers vs References

```cpp
int x = 5;
int* p = &x;
int& ref = x;
```

| Feature         | Pointer         | Reference    |
| --------------- | --------------- | ------------ |
| Null            | Yes (`nullptr`) | No           |
| Reassignment    | Yes             | No           |
| Must initialize | No              | Yes          |
| Syntax          | `*p`, `&var`    | `&ref = var` |

Use **pointers** when you want reassignable access or optional ownership. Use **references** for guaranteed binding and simplicity.

#### 3.5 `nullptr`, `void*`, and `restrict`

* `nullptr`: Type-safe null pointer (introduced in C++11).
* `void*`: Generic pointer, must cast before dereferencing.
* `restrict` (non-standard in C++): Tells the compiler that the pointer is the only one accessing that memory location (can improve optimizations).

***

### 4. Stack vs Heap Memory

| Feature    | Stack              | Heap                       |
| ---------- | ------------------ | -------------------------- |
| Alloc Time | Fast (LIFO)        | Slower (malloc/new)        |
| Size       | Limited (\~1–8 MB) | Large (OS-managed)         |
| Lifetime   | Auto-managed       | Manual or smart pointers   |
| Access     | Cache-friendly     | Fragmented, less cacheable |

#### Performance Insight:

* Prefer stack for small, short-lived objects.
* Heap adds indirection, cache misses, and malloc/free overhead.

***

### 5. Smart Pointers

#### 5.1 `std::unique_ptr`

```cpp
std::unique_ptr<int> p = std::make_unique<int>(10);
```

* Single ownership, no copy.
* Auto deletes on scope exit.

#### 5.2 `std::shared_ptr`

```cpp
std::shared_ptr<int> p = std::make_shared<int>(10);
```

* Reference-counted.
* Slight overhead due to atomic operations.

#### 5.3 When to Use:

| Use Case                 | Smart Pointer      |
| ------------------------ | ------------------ |
| Exclusive ownership      | `unique_ptr`       |
| Shared ownership         | `shared_ptr`       |
| Polymorphic base cleanup | `unique_ptr<Base>` |

***

### <mark style="background-color:orange;">6.</mark> <mark style="background-color:orange;"></mark><mark style="background-color:orange;">`new`</mark><mark style="background-color:orange;">,</mark> <mark style="background-color:orange;"></mark><mark style="background-color:orange;">`delete`</mark><mark style="background-color:orange;">, and Memory Pitfalls</mark>

#### <mark style="background-color:orange;">6.1 Placement New</mark>

```cpp
char buffer[sizeof(int)];
int* p = new (buffer) int(10); // constructs in pre-allocated memory
```

<mark style="background-color:orange;">Used in custom allocators, memory pools, and embedded systems.</mark>

#### <mark style="background-color:orange;">6.2 Overloading new/delete</mark>

```cpp
void* operator new(std::size_t size) {
    std::cout << "Allocating " << size << " bytes\n";
    return malloc(size);
}
```

<mark style="background-color:orange;">Advanced use-case: profiling, debugging memory leaks, etc.</mark>

***

### 7. Trick Questions

#### Q1. What does this print?

📚 *Source: StackOverflow C++ Trivia*

```cpp
int* p = new int(10);
*p += 5;
std::cout << *p;
delete p;
```

**Answer:** 15

***

#### <mark style="color:yellow;">Q2. Can a pointer point to a pointer?</mark>

```cpp
int x = 42;
int* p = &x;
int** pp = &p;
std::cout << **pp;
```

**Answer:** Yes → prints 42

***

#### Q3. Is this UB?

```cpp
int arr[3] = {1,2,3};
int* p = arr + 3;
std::cout << *(p);  // is this legal?
```

**Answer:** Undefined Behavior — accessing one past the end.

***

#### Q4. What is wrong with this?

```cpp
int* p;
*p = 5;
```

**Answer:** UB — pointer `p` is uninitialized. Always initialize pointers.

***

#### Q5. What's the size of a pointer?

```cpp
std::cout << sizeof(int*);
```

**Answer:** Typically 4 bytes (32-bit) or 8 bytes (64-bit). Platform-dependent.

***

### 8. Summary

| Concept       | Best Practice / Tip                            |
| ------------- | ---------------------------------------------- |
| Arrays        | Use `std::vector` over raw pointers            |
| Strings       | Avoid mixing C-strings and `std::string`       |
| Pointers      | Initialize before use, prefer smart ptrs       |
| Stack vs Heap | Use stack unless dynamic size needed           |
| Smart Ptrs    | `unique_ptr` preferred unless sharing req      |
| const         | Understand binding direction with pointers     |
| new/delete    | Match properly, use smart ptrs when possible   |
| References    | Use when ownership or nullability isn't needed |

***

Next: Chapter 7 — Pointers to Functions, Lambdas, and Advanced Call Mechanics
