Bino Manjesh
Bino Manjesh

Reputation: 23

Can pointers be used for accessing any arbitrary area in memory?

I am extremely new to C++ and pointers.

#include <iostream>

using namespace std;

int main() {
    char* c = "my name jeff";
    int i = 0;
    while (true) {
        cout << *(c + i++);
    }
    return 0;
}

The output is "my name jeff" followed by a lot of random characters, occasionally making sense. Am I actually accessing memory in my computer ? Why can initialize a pointer from a string ?

Upvotes: 1

Views: 626

Answers (2)

user10957435
user10957435

Reputation:

First, a note about this line right here:

char* c = "my name jeff";

In modern C++, this should be a const instead:

const char* c = "my name jeff";

With that out of the way, the answer to your question is yes and no.

Yes in the sense that if you have some sort of pointer, C++ doesn't care what you put in it.

char * pointer = nullptr;
char a, b, c;

pointer = &a;
pointer = &b;
pointer = &c;

The pointer doesn't care what address is stored in it. It is arbitrary in that sense. As long as it is the same type, you're fine.

You can even do pointer arithmetic like this:

*(pointer + 1) = 1;
*(pointer + 2) = 2;
*(pointer + i) = i;

In most cases, this will usually at least compile and probably run. In theory, you could use this type of arithmetic to access any given address and see what data is stored there.

However, in practice, the answer is a big no. That is because accessing unallocated memory is undefined behavior in C++. If you're unaware, undefined behavior allows anything to happen, including crashing or printing weird characters.

So, if you have some array like this:

int arr[4] = {1,2,3,4};
int * pointer = arr;

std::cout << *(pointer + 7);

This is undefined behavior because only pointer + 3 is guaranteed to have allocated memory in it.

So, in short: Yes, you can theoretically reach any address you want with pointer arithmetic, but you can only access memory that has been allocated safely. So in practice, not really.

Upvotes: 1

Jarod42
Jarod42

Reputation: 217245

From https://eel.is/c++draft/expr#add-4

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.

(4.1) If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.

(4.2) Otherwise, if P points to an array element i of an array object x with n elements ([dcl.array]),77 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) array element i + j of x if 0 ≤ i + j ≤ n and the expression P - J points to the (possibly-hypothetical) array element i − j of x if 0 ≤ i − j ≤ n .

(4.3) Otherwise, the behavior is undefined.

So, with "my name jeff" (which is of type const char[13] (with the extra '\0')), once you do c[14] you have UB.

Upvotes: 2

Related Questions