Real-world Examples of Pointer Arithmetic and Its Pitfalls in C and C++

Pointer arithmetic is a common feature in C and C++, allowing direct manipulation of memory addresses. While powerful, improper use can lead to bugs, security vulnerabilities, and undefined behavior. This article presents real-world examples illustrating both the applications and pitfalls of pointer arithmetic.

Example 1: Traversing Arrays

Pointer arithmetic is often used to iterate through arrays efficiently. For example, to sum elements of an integer array:

Correct usage:

int sum = 0;

int *ptr = array;

for (int i = 0; i < size; i++) {

sum += *(ptr + i);

}

This method correctly accesses array elements using pointer arithmetic.

Pitfall 1: Pointer Arithmetic Beyond Array Bounds

Moving pointers beyond the allocated memory can cause undefined behavior. For example:

int *ptr = array;

for (int i = 0; i <= size; i++) {

printf(“%dn”, *(ptr + i));

}

Accessing *(ptr + size) exceeds array bounds, leading to unpredictable results.

Example 2: String Manipulation

Pointer arithmetic is frequently used in string processing. For example, copying a string:

Correct approach:

char *src = “Hello”;

char dest[6];

char *p = src;

char *q = dest;

while (*p) {

*q++ = *p++;

}

*q = ”;

Pitfall 2: Off-by-One Errors in String Copying

Failing to allocate space for the null terminator or copying beyond the buffer causes buffer overflows. For example:

char dest[5];

char *p = “World”;

for (int i = 0; i <= 5; i++) {

dest[i] = p[i];

}

This copies six characters into a five-character buffer, causing overflow.

Conclusion

Pointer arithmetic provides flexibility in C and C++, but it requires careful handling to avoid errors. Understanding common pitfalls helps prevent bugs and security issues in software development.