Home > Mobile >  Why c no more shows index out of range on giving index for accessing character of a string, which
Why c no more shows index out of range on giving index for accessing character of a string, which

Time:04-15

Think C Allen B. Downey, chapter 7, section 7.6 A run-time error

After reading the excerpt about run time error and index out of range error in c . I tried to execute the same in my compiler of c which is running in vs code. But even on trying positive out of range index as well as negative index. I wasn't getting any error instead getting an unexpected (erronous) character being printed on the console. The code I was trying to run is:

int main();
{
string user_input = "hello";
char a = user_input[100];
cout << a << endl;
return 0;
}

positive index out of range was giving new line as the output. While negative index out of range (like -100) was each time giving different character on the console. Please explain the correct behaviour of c and why current c is not working as written in book? Is the book incorrect or it is recent version thing.

CodePudding user response:

When you wrote:

char a = user_input[100];//this is undefined behavior

The expression user_input[100] leads to undefined behavior because you're going out of range of the std::string. If you want to make sure that you get an error while accessing out of range elements, then you can use std::string::at member function like:

user_input.at(100)//this will perform bound checking and throw exception on invalid access

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

CodePudding user response:

Technically when you access a character outside the valid range of a string, you're getting undefined behavior. The funny thing about undefined behavior is that it's completely undefined; you could get something reasonable, you could get total gibberish, your program could crash, or you could get demons flying from your nostrils. All of those are valid responses to undefined behavior, and they need not be consistent from one run to the next.

Any reference you find that claims a particular result for undefined behavior is lying.

  •  Tags:  
  • c
  • Related