-2

My program is crashing when I run it, I ran the debugger and it reports this: std::out_of_range at memory location 0x0066F6F4.

My code is as follows:

#include <iostream>
#include <string>

int main() {
    std::string name = "Alexi";

    for (unsigned int i = 0; i <= name.length(); i++) {
        for (unsigned int x = 0; x <= i; x++)  {
            if (i == x) std::cout << name.at(x);
            else std::cout << " ";
        }
        std::cout << '\n';
    }

    return 0;
}

Any help would be appreciated.

  • 2
    Sigh. `i <= name.length()` makes you iterate one too many times and access out of bounds. – juanchopanza Jan 22 '15 at 22:43
  • 1
    C++ arrays are [0-indexed](http://en.wikipedia.org/wiki/Zero-based_numbering) meaning that while the length is 5, the index starts from 0 and goes to 4. Therefore you need to stop your loop iteration 1 before length (ie: `i < name.length()`) – Steve Lorimer Jan 22 '15 at 22:57
  • 1
    @ElliottFrisch `'\n'` is not platform-specific. The I/O system *has to* translate it to whatever is appropriate for expressing a newline. Actually, `'\n'` is preferable in certain situations (since it doesn't force flushing the stream like `std::endl` does). – The Paramagnetic Croissant Jan 22 '15 at 23:01
  • 1
    @ElliottFrisch `\n` **is** the newline in C, and that *`\n` to platform specific line terminator conversion* is handled by the stream [related question](http://stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco) – Steve Lorimer Jan 22 '15 at 23:02
  • I don't think the downvotes are justified. OP gave a fully working example showing the problem. Just because it's a relatively simple problem with a simple fix doesn't mean it's not worthy of SO – Steve Lorimer Jan 22 '15 at 23:03

2 Answers2

4

You should have i < name.length() and not i <= name.length()

#include <iostream>
#include <string>

int main() {
    std::string name = "Alexi";

    for (unsigned int i = 0; i < name.length(); i++) {
        for (unsigned int x = 0; x <= i; x++)  {
            if (i == x) std::cout << name.at(x);
            else std::cout << " ";
        }
        std::cout << '\n';
    }

    return 0;
}
Jérôme
  • 8,016
  • 4
  • 29
  • 35
2

The string name has the length of 5.

Internally, it is stored in a char [] (character array) called namewhere the

  • character A is stored at name[0]
  • character l is stored at name[1]
  • character e is stored at name[2]
  • character x is stored at name[3]
  • character i is stored at name[4]

So note that the length was 5 but your maximum index is 4.

This is because C and C++ arrays are 0-indexed

Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
Ehsan Ab
  • 679
  • 5
  • 16