c++outofrangeexception

Terminating with uncaught exception of type std::out_of_range aborted error


I'm trying to make a program that turns a string into a char array. My code looks something just like this (this is just a part of my code):

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string Word;
    cout << "Type A String And I'll Turn It Into A Char Array ' : ";
    cin >> Word;
    int Length = Word.length();
    char Char_Word[Length];
    //Looping To Set The String Characters To A Char Array
    for (int CharSet = 0; CharSet <= Length; CharSet++)
    {
        Char_Word[CharSet] = Word.at(CharSet);
    }
}

But when I run this code and give it an input it outputs this statement

terminating with uncaught exception of type std::out_of_range: basic_string Aborted

ERROR

Idk why this happens. Pls help me fix it, and thanks ya for reading it.


Solution

  • You are writing out of the range of char_word variable.

    //First make enough space for char_word
    int length = word.length()+1;
    char Char_word[ length ];
    for( int i = 0; i < length - 1; i++)
         Char_word[i] = word.at(i);
    Char_word[length-1] = '\0'; //very important
    

    Reading or writing beyond the range is a bad thing in C/C++. It's a good point a hacker can exploit to make ill your program... NB: I didn't test it... I wrote directly from my phone