Ugenz Academy/IoT Tutorial

Pointers And Memory Basics

19 min read3,727 words

Reading progress

Keep learning

Pointers and Memory Basics in ESP32 Programming

Pointers and memory management are important concepts in C and C++ programming. They help you understand how data is stored, how functions can access existing variables, and how programs work with arrays, objects, and hardware-related data.

In ESP32 programming, these concepts become especially useful when working with sensor data, buffers, communication protocols, libraries, and memory-limited applications.

In this lesson, you will learn pointers from the basics, understand memory addresses, use pointers with variables and arrays, explore stack and heap memory, and learn common mistakes to avoid when developing ESP32 projects.

1. What Is Memory?

Memory is the part of a computer or microcontroller where program instructions and data are stored while the device operates.

The ESP32 uses different types of memory for different purposes.

Common memory types include:

  • RAM: Stores variables and other data that the program needs while running.
  • Flash memory: Stores program code and persistent read-only data.
  • Stack: Holds function-call information and many local variables.
  • Heap: Provides memory for dynamic allocation at runtime.
  • Registers: Small, fast storage locations used by the processor and peripherals.

The exact memory layout depends on the ESP32 model, framework, compiler, and configuration.

Example: A Variable in Memory

void setup() { Serial.begin(115200); int temperature = 25; Serial.println(temperature); } void loop() { }

The variable temperature stores the integer value 25.

The compiler and runtime determine where this variable is stored. Because it is a local variable inside setup(), it will commonly be stored in stack memory, although compiler optimizations can change how a variable is represented.

2. What Is a Memory Address?

Every addressable location in memory has an address that can be used to identify it.

For example, imagine that an integer variable is stored at a fictional address:

Variable: temperature Value: 25 Address: 0x3FFB1000

The address shown above is only an illustration. Actual addresses vary between executions, devices, and memory regions.

In C++, the address-of operator & lets you obtain the address of an object.

Example: Display a Variable's Address

void setup() { Serial.begin(115200); int temperature = 25; Serial.print("Value: "); Serial.println(temperature); Serial.print("Address: "); Serial.println( reinterpret_cast<uintptr_t>(&temperature), HEX ); } void loop() { }

Explanation

  • temperature refers to the variable's value.
  • &temperature obtains the variable's address.
  • uintptr_t is an unsigned integer type, when available, that can hold a converted pointer representation.
  • HEX displays the converted address in hexadecimal notation.

This example also uses uintptr_t, which is declared in the standard C++ header <cstdint> when the implementation provides it. For portable code, include that header explicitly:

#include <cstdint>

Addresses are useful when learning pointers and debugging memory-related behavior. However, an address alone does not tell you whether the memory is valid to access.

3. What Is a Pointer?

A pointer is a variable that stores the address of an object or function.

A normal variable stores a value directly. A pointer stores an address that can be used to access another object.

Normal Variable

int number = 10;

Here, number stores the integer value 10.

Pointer Variable

int number = 10; int *ptr = &number;

Here:

  • number stores 10.
  • &number obtains the address of number.
  • ptr stores that address.
  • *ptr accesses the value of the object pointed to by ptr.

Basic Pointer Example

void setup() { Serial.begin(115200); int number = 10; int *ptr = &number; Serial.print("Number: "); Serial.println(number); Serial.print("Value through pointer: "); Serial.println(*ptr); } void loop() { }

Output:

Number: 10 Value through pointer: 10

Both expressions access the same integer value.

4. Understanding & and *

Two operators are especially important when learning pointers.

The Address-of Operator &

The address-of operator obtains the address of an object.

int number = 50; int *ptr = &number;

In this example, &number means the address of number.

The Dereference Operator *

When used with a valid pointer, the dereference operator accesses the object at the address stored in that pointer.

int number = 50; int *ptr = &number; Serial.println(*ptr);

The expression *ptr produces the value 50.

The symbol * has two different uses in these examples:

int *ptr = &number; // Declares a pointer Serial.println(*ptr); // Dereferences the pointer

The first declares ptr as a pointer to an integer. The second accesses the integer through that pointer.

5. Modifying a Variable Through a Pointer

A pointer can be used to modify the original variable it points to.

Example

void setup() { Serial.begin(115200); int number = 10; int *ptr = &number; *ptr = 99; Serial.print("Number: "); Serial.println(number); } void loop() { }

Output:

Number: 99

The statement *ptr = 99 changes the object pointed to by ptr. Since ptr points to number, the original variable becomes 99.

This behavior is useful when functions need to modify existing data without returning a replacement value.

6. Pointer Declaration Syntax

The general syntax for declaring a pointer is:

dataType *pointerName;

Examples:

int *intPointer; float *floatPointer; char *charPointer; bool *boolPointer;

Each pointer type is designed to point to objects of a compatible type.

For example, an int* normally points to an integer, while a float* points to a floating-point object.

Important Note About Declaration Style

These two declarations are equivalent:

int* ptr; int *ptr;

However, in the following statement, only ptr1 is a pointer:

int *ptr1, value;

The variable value is an ordinary integer.

For clarity, especially when teaching or reading code, declare pointers separately:

int *ptr1; int value;

7. Null Pointers

A null pointer does not point to a valid object.

In modern C++, use nullptr to initialize a pointer when it does not yet point to an object.

int *ptr = nullptr;

You can check whether the pointer is null before using it.

Example

void setup() { Serial.begin(115200); int *ptr = nullptr; if (ptr != nullptr) { Serial.println(*ptr); } else { Serial.println("Pointer is not initialized."); } } void loop() { }

Output:

Pointer is not initialized.

Dereferencing a null pointer is invalid and causes undefined behavior. Always ensure a pointer refers to a valid object before accessing it.

8. Pointers and Functions

Pointers allow functions to access or modify existing objects.

Example: Modify a Value

void increaseValue(int *ptr) { if (ptr != nullptr) { *ptr = *ptr + 1; } } void setup() { Serial.begin(115200); int number = 10; increaseValue(&number); Serial.println(number); } void loop() { }

Output:

11

Explanation

  1. The variable number starts at 10.
  2. &number passes its address to increaseValue().
  3. The parameter ptr receives the address.
  4. *ptr accesses the original variable.
  5. The function increases the original value to 11.

A pointer parameter can be useful when a function needs to modify an existing object or when an API is designed to accept optional objects.

For simple cases like this, a C++ reference parameter is often easier to use:

void increaseValue(int &number) { number++; }

Both approaches can modify the original integer, but their interfaces communicate different intent.

9. Pointers and Arrays

Pointers and arrays are closely related in C++.

In many expressions, the name of an array converts to a pointer to its first element. This is commonly called array-to-pointer decay.

Example

void setup() { Serial.begin(115200); int numbers[4] = {10, 20, 30, 40}; int *ptr = numbers; Serial.println(*ptr); Serial.println(*(ptr + 1)); Serial.println(*(ptr + 2)); Serial.println(*(ptr + 3)); } void loop() { }

Output:

10 20 30 40

Here, ptr points to the first element of numbers.

The expressions ptr + 1, ptr + 2, and ptr + 3 refer to successive elements of the array. Pointer arithmetic automatically accounts for the size of the pointed-to type.

Array Indexing and Pointers

For a valid array element, these expressions are equivalent:

numbers[0] *(numbers + 0)

Similarly:

numbers[2] *(numbers + 2)

Both access the third element.

Important: Pointer arithmetic and array indexing are only valid within the permitted bounds of the array, including forming a pointer one position past the end for limited purposes. Dereferencing that one-past-the-end pointer is invalid.

10. Using Pointers to Process Sensor Data

Pointers can be useful when a function processes an array of readings.

Example: Calculate the Sum of Sensor Readings

long calculateSum(const int *values, int count) { if (values == nullptr || count <= 0) { return 0; } long total = 0; for (int i = 0; i < count; i++) { total += values[i]; } return total; } void setup() { Serial.begin(115200); int readings[4] = {100, 200, 300, 400}; long total = calculateSum(readings, 4); Serial.print("Total: "); Serial.println(total); } void loop() { }

Output:

Total: 1000

How It Works

  • readings converts to a pointer to its first element when passed to the function.
  • const int *values allows the function to read the array elements without modifying them through that pointer.
  • count tells the function how many elements it may process.
  • The loop adds the elements and returns the total.

A pointer does not contain the array's length. That is why the function receives count separately.

The caller must ensure that the supplied count matches the number of accessible elements.

11. Pointers to Characters and Strings

Pointers are commonly used when working with C-style strings.

A C-style string is a sequence of characters ending with the null character '\0'.

Example

void setup() { Serial.begin(115200); const char *message = "Hello ESP32"; Serial.println(message); } void loop() { }

Output:

Hello ESP32

Here, message points to the first character of a string literal.

The const qualifier is important because string literals must not be modified. Attempting to change a string literal through a non-const pointer is invalid.

Character-by-Character Access

void setup() { Serial.begin(115200); const char *message = "ESP32"; for (int i = 0; message[i] != '\0'; i++) { Serial.println(message[i]); } } void loop() { }

Output:

E S P 3 2

The loop continues until it encounters the null terminator.

For editable text, use a writable character array with enough capacity:

char message[] = "ESP32"; message[0] = 'e';

This modifies the array to contain eSP32. Do not attempt the same modification on a string literal.

12. Pointer to Pointer

A pointer to pointer stores the address of another pointer.

Example

void setup() { Serial.begin(115200); int number = 25; int *ptr = &number; int **ptrToPtr = &ptr; Serial.println(number); Serial.println(*ptr); Serial.println(**ptrToPtr); } void loop() { }

Output:

25 25 25

Explanation

  • ptr points to number.
  • ptrToPtr points to ptr.
  • *ptr accesses number.
  • **ptrToPtr accesses number through both pointer levels.

Pointers to pointers are useful in some C APIs, dynamic data structures, and functions that need to modify a pointer variable itself. They are more advanced and are not necessary for every ESP32 project.

13. What Is Stack Memory?

The stack is a memory region used for function-call information and commonly for local variables.

When a function is called, the program needs to keep track of information such as where to return after the function finishes.

Example

void displayValue() { int number = 10; Serial.println(number); } void setup() { Serial.begin(115200); displayValue(); } void loop() { }

The local variable number is associated with the function's scope and commonly stored on the stack.

When displayValue() returns, its local variable's lifetime ends.

You should not return a pointer to a local variable that has gone out of scope.

Incorrect Example

int* getValuePointer() { int number = 10; return &number; }

The returned pointer becomes invalid after the local variable's lifetime ends. Dereferencing it later causes undefined behavior.

Safer Alternative

Return the value itself:

int getValue() { int number = 10; return number; }

The caller receives a copy of the integer, so it does not depend on the lifetime of a local variable.

14. What Is Heap Memory?

The heap is a memory region used for dynamic allocation. Dynamic allocation lets a program request memory while it is running.

In C++, the operators new and delete are traditionally used for dynamic allocation and deallocation.

Example: Dynamic Integer Allocation

void setup() { Serial.begin(115200); int *ptr = new int(50); Serial.print("Value: "); Serial.println(*ptr); delete ptr; ptr = nullptr; } void loop() { }

Output:

Value: 50

Explanation

  1. new int(50) allocates an integer and initializes it to 50.
  2. The pointer stores the address of that integer.
  3. *ptr accesses the allocated value.
  4. delete ptr releases the allocated object.
  5. Assigning nullptr prevents the local pointer from retaining the old address.

After an object is deleted, its former address must not be dereferenced. Setting the pointer to null does not affect other pointers that might refer to the same object.

ESP32 best practice: Dynamic allocation is sometimes useful, but repeated allocations and deallocations can fragment the heap. In embedded applications, prefer fixed-size buffers and predictable memory use when practical.

Always check allocation success when using allocation mechanisms that may fail on your platform. On many embedded C++ configurations, a failed new allocation may throw an exception or follow the configured failure behavior, so do not assume it simply returns nullptr.

15. Static and Global Memory

Global and static variables have static storage duration, meaning their lifetime extends throughout the program's execution.

Example

int totalReadings = 0; void recordReading() { static int callCount = 0; callCount++; totalReadings++; Serial.print("Function calls: "); Serial.println(callCount); } void setup() { Serial.begin(115200); recordReading(); recordReading(); recordReading(); } void loop() { }

Output:

Function calls: 1 Function calls: 2 Function calls: 3

The local static variable callCount retains its value between function calls. The global variable totalReadings is accessible from other functions in its scope.

Static and global variables can be useful for counters and application state, but avoid making all variables global. Excessive global state can make programs difficult to test and maintain.

16. Stack vs. Heap vs. Static Memory

FeatureStackHeapStatic storage
Typical purposeFunction calls and local dataDynamic allocationGlobal and static variables
LifetimeOften tied to scope or function callsUntil explicitly released or otherwise managedEntire program execution
AllocationCommonly automaticRequested at runtimeEstablished for static storage duration
Common concernStack overflowFragmentation and leaksPersistent memory consumption

These descriptions are conceptual. The actual location of an object depends on the C++ implementation, optimization, and ESP32 memory configuration.

17. Memory Leaks

A memory leak occurs when dynamically allocated memory is no longer reachable or is never released even though the program no longer needs it.

Example of a Leak

void createData() { int *ptr = new int(100); // The allocated memory is never released. }

When the function returns, the local pointer disappears, but the dynamically allocated integer remains allocated. The program has lost its pointer to that allocation, so it cannot release the memory through that pointer.

If this happens repeatedly in a long-running ESP32 project, available heap memory can decrease over time.

Corrected Example

void createData() { int *ptr = new int(100); Serial.println(*ptr); delete ptr; }

In modern C++, resource-management techniques such as RAII and smart pointers can reduce these risks when supported by the project configuration. On embedded systems, a fixed-size design may be simpler and more predictable.

18. Dangling Pointers

A dangling pointer is a pointer that refers to an object whose lifetime has ended or whose storage is no longer valid.

Example of the Problem

int* createPointer() { int number = 20; return &number; }

The local variable stops existing when the function returns. The returned pointer is therefore invalid.

Safer Alternative

int createValue() { int number = 20; return number; }

Return a value when the caller only needs the result.

Another common source of dangling pointers is using a pointer after the object it refers to has been deleted.

int *ptr = new int(20); delete ptr; ptr = nullptr;

After deletion, do not access the object through ptr or through any other pointer to the same deleted object.

19. Avoiding Buffer Overflows

A buffer overflow occurs when a program writes beyond the valid bounds of a buffer.

For example, if an array contains five integers, its valid indexes are 0 through 4.

Incorrect Example

int values[5] = {1, 2, 3, 4, 5}; values[5] = 100; // Out of bounds: invalid access

The last valid element is values[4].

Correct Example

int values[5] = {1, 2, 3, 4, 5}; values[4] = 100;

Out-of-bounds access causes undefined behavior and can lead to crashes, corrupted data, or security vulnerabilities.

For ESP32 applications that process serial commands, network packets, or sensor messages, validate lengths before copying or accessing buffer data.

20. Pointer Safety Checklist

Before using a pointer, consider the following questions:

  1. Has the pointer been initialized?
  2. Does it point to a valid object?
  3. Is the object's lifetime still active?
  4. Is the pointer type compatible with the object?
  5. If accessing an array, is the index within bounds?
  6. If the memory was dynamically allocated, who is responsible for releasing it?
  7. Could the pointer become invalid after a function returns or an object is destroyed?
  8. Is the memory writable, or should it be treated as read-only?

Following these checks helps avoid many common memory errors.

21. Practical ESP32 Example: Processing a Sensor Buffer

This example collects a small number of analog readings into a fixed-size array and passes the array to a function for analysis.

const int SENSOR_PIN = 34; const int SAMPLE_COUNT = 5; int readings[SAMPLE_COUNT]; long calculateSum(const int *values, int count) { if (values == nullptr || count <= 0) { return 0; } long total = 0; for (int i = 0; i < count; i++) { total += values[i]; } return total; } void collectReadings() { for (int i = 0; i < SAMPLE_COUNT; i++) { readings[i] = analogRead(SENSOR_PIN); delay(50); } } void setup() { Serial.begin(115200); pinMode(SENSOR_PIN, INPUT); } void loop() { collectReadings(); long total = calculateSum(readings, SAMPLE_COUNT); float average = static_cast<float>(total) / SAMPLE_COUNT; Serial.print("Average sensor reading: "); Serial.println(average); delay(1000); }

How It Works

  1. The global array readings reserves space for five integers.
  2. collectReadings() fills the array with analog readings.
  3. calculateSum() receives a pointer to the first element and a count.
  4. The function calculates the sum without modifying the readings.
  5. loop() calculates and displays the average.

This example uses a fixed-size buffer, avoiding repeated heap allocation.

The input pin and ADC range must be appropriate for your ESP32 model and sensor. The delay() calls are used for simplicity; a time-sensitive application could use millis() instead.

22. Common Pointer Mistakes

Mistake 1: Dereferencing an Uninitialized Pointer

Incorrect:

int *ptr; *ptr = 10;

The pointer does not point to a known valid object.

Correct:

int number = 0; int *ptr = &number; *ptr = 10;

Mistake 2: Dereferencing nullptr

Incorrect:

int *ptr = nullptr; Serial.println(*ptr);

Correct:

int *ptr = nullptr; if (ptr != nullptr) { Serial.println(*ptr); }

This check is useful only if the pointer's value is meaningful to test; it does not guarantee that every non-null pointer is valid.

Mistake 3: Returning a Pointer to a Local Variable

Do not return the address of a local variable whose lifetime ends when the function returns. Return the value or use an object with an appropriate lifetime.

Mistake 4: Forgetting to Release Dynamically Allocated Memory

If you allocate an object using new, ensure its lifetime is managed correctly. Prefer automatic objects or RAII techniques where suitable.

Mistake 5: Accessing an Array Outside Its Bounds

Always verify the index and the number of elements before accessing an array through a pointer.

Mistake 6: Modifying Read-Only Data

Do not modify a string literal through a pointer. Use a writable character array when modification is required.

23. Practice Exercises

Beginner

  1. Create an integer variable and print its value and address.
  2. Create an integer pointer and use it to read the original variable.
  3. Change a variable's value through a pointer.
  4. Initialize a pointer with nullptr and safely check it before use.

Intermediate

  1. Write a function that accepts an integer pointer and updates the value.
  2. Use a pointer to print all elements of an integer array.
  3. Create a function that calculates the sum of an array using a pointer and an element count.
  4. Print the characters of a C-style string using a pointer or array indexing.

Advanced

  1. Explain why returning the address of a local variable is unsafe.
  2. Compare stack, heap, and static storage duration.
  3. Demonstrate a memory leak and correct it.
  4. Build an ESP32 sensor-buffer program that uses a fixed-size array and a function to calculate an average.
  5. Explain why array bounds must be checked when processing serial or network input.

Summary

Pointers store addresses and allow programs to access objects indirectly. They are fundamental to understanding arrays, function interfaces, C-style strings, and many low-level programming techniques.

In this lesson, you learned:

  • Memory addresses and pointer declarations.
  • The address-of (&) and dereference (*) operators.
  • Null pointers and safe pointer access.
  • Pointers with functions and arrays.
  • Character pointers and C-style strings.
  • Pointer-to-pointer concepts.
  • Stack, heap, and static memory.
  • Dynamic allocation and memory leaks.
  • Dangling pointers and buffer overflows.
  • Safe use of fixed-size buffers in ESP32 projects.

Key principle: A pointer is useful only when it refers to a valid object whose lifetime and bounds are respected. In ESP32 development, predictable memory use and careful pointer handling help build stable, reliable IoT applications.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy