jeudi 17 août 2017

For-Loop on Pointer: Does it move the whole address range?

I have this bit of code:

int count_x(char* p, char x)
{
  if (p == nullptr) return 0;

  int count = 0;

  for (; *p != 0; p++)
  {
    if (*p == x)
    count++;
  }
  return count;
}

The input is in this case a char-array:

char v[] = { "Ich habe einen Beispielsatz erstellt!"};

Since I am currently looking into CPP with the book "C++ the programming language - 4th Edition" I got the code from there and am currently trying to figure it out.

When stepping through it, I noticed that the for loop moves the memory address in increments of one. This is not very surprising to me, but the following question arose and I couldn't find an answer yet: Does this loop reduce the overall memory range or is the whole range being moved?

Since to my knowlege you use a "block" in whole for storing such a char-array (or any type of array), I guess it is the later since I don't see anything reducing the boundries. But with that "knowledge" I have to ask: Doesn't this cause major issues as it would be theoretically possible to read parts of the memory the programm shouldn't have access to?

Will this be something I have to keep in mind when dealing with (very) long arrays?

Aucun commentaire:

Enregistrer un commentaire