-2

When I write this code everything seems to work perfect

string *s;
s=new string("some_string");
*(s+1) = *s;

But when I replace "some_string" with blank my programm throws segmetation fault. Why is this happening and is there a way to fix it???

s=new string("");

2 Answers2

-1

I think the problem is the last line of your code as *(s+1) should have generated an error or exception even before,when "some_string" was initialized as string. There wont be any string at (s+1) when you initialized the pointer as *s

Logical Retard
  • 113
  • 2
  • 11
  • 1
    The compiler is not required to warn/error when you go out of the bounds of an array. It is also not required to throw an exception. The best you can hope for is a seg fault or memory violation. – NathanOliver Jun 02 '17 at 13:54
  • @NathanOliver wouldn't it generate an arrayoutofbound exception if the array size exceeds what is specified or more memory is being tried to access than what is allocated? – Logical Retard Jun 02 '17 at 13:59
  • Nope. See: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – NathanOliver Jun 02 '17 at 14:00
  • @LogicalRetard: There is no "arrayoutofbound exception" in C++. You must be thinking of Java or C#. Wrong language! – Christian Hackl Jun 02 '17 at 14:51
-1

The output of your program will depend on compiler.

Type of the expression *(s+1) is string, so what you do with *(s+1) = * s is: First, you try to cast *(s+1) to a string, then you try to assign that string to *s, which will call the copy constructor of that newly casted string.

When the string is not empty, the compiler may allocate more memory than what is needed to store *s's data ("some_string"), and the copy function in string only runs through its real data ("some_string") which means it doesn't access any memory further than what was allocated by *s.

But when the string is empty, the compiler doesn't allocate that much memory, which causes the segment fault error.

So the result of your program may depend on compiler, how they reserve data for std::basic_string and how they store it.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • This answer is very misleading. The code is simply undefined behaviour. There is no casting involved, there is no copy constructor call and even the explanation of the crash in terms of implementation details is not necessarily correct when you consider SSO. – Christian Hackl Jun 02 '17 at 14:56