Sumit Kumar Sumit Kumar - 1 month ago 4
C Question

Unusual behaviour of strings

using namespace std;
int main(void)
char a[10]="Rosewater";
char b[3];

int i=0;
b[i]=a[i]; //1. does not throw an error


ewsewater // value of a also changed

Rosewsewater // unclear output


//1. does not throw an error

In C and in C++ there is no bounds check because it is simply exposing raw memory.

That what is defined as Undefined Behaviour. That means (in very short) that the standard does not specify what will happen in your program, anything could happen when an instruction produces an undefined behaviour.

My suggest if you're using C++ (which is a different language from C) is to use std::vector class. Here References.

Note that std::vector produces an undefined behaviour when you try to access to a index out of bounds. With the method at, instead, an exception will throw in that case.

#include <vector>

int main(int argc, char* argv[]) {
  std::vector<char> a = {'a', 'b', 'c'};;  // it will throw an exception
  return 0;

Moreover, if you have to manage strings the most convenient class is std::string.