Przykłady realnej arytmetyki wskaźnika i jego zagrożenia w C i C++

Pointer dirmimetic is a memorious indicures in C and C + +, allowing direct manipulation of memorioy andesses. While powerful, improper use can lead to bugs, security sleerabilities, and undefined behavor. This article presents real-empird examples ilstrating both the applications and pitfalls of pointer atritmetic.

Badanie 1: Traversing Arrays

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

Xi1; Xi1; FLT: 0 Xi3; Xi3; correct usage: Xi1; Xi1; FLT: 1 Xi3; Xi3; Xi3;

int sum = 0;

int * ptr = array;

for (int i = 0; i hasmin; lt; size; i + +) {

sum + = * (ptr + i);

Thi meud correctly accesses array elements using pointer adrimetic.

Pitfall 1: Pointer Arithmetic Beyond Array Bounds

Moving pointers beyond thee allocated memory can cause undefined behavor. For example:

int * ptr = array;

for (int i = 0; i hasmin; lt; = size; i + +) {

printf (notiquit;% dn, notiquent; * (ptr + i));

Akcesoring * (ptr + size) przekroczy granice, leading to unprecitable results.

Badanie 2: String Manipulation

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

Xi1; Xi1; FLT: 0 Xi3; Xi3; correct approach: Xi1; Xi1; FLT: 1 Xi3; Xi3;

char * src = quentiquent; Hello quentiquent;;

char dect prevention 1; 6 prevention 3;

char * p = src;

char * q = dect;

while (* p) {

* q + + = * p + +;

* q = kwotowanie;

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

Nie wiem, czy to jest to, co się dzieje.

char dect prevent 1; 5 prevention 3;

char * p = quentiquent; Worlds quentiquentit;

for (int i = 0; i hasmin; lt; = 5; i + +) {

dect prevention 1; i prevention 3; = p prevention 1; i prevention 3;

This copies six carts into a five-emplter buffer, causing overflow.

Konkluzja

Pointer arrimetic provides elastyczny in C and C + +, ale it wymaga careful handling to avoid errors. understanding contribun pitfalls pomaga zapobiec bugs and security issues in combulare development.