Q:

Why does cout << *s << endl produce a segfault?

I have this question on a practice exam for my C++ class, we're supposed to write what the output is or if it produces an error. Running this code produces a segmentation fault, but can someone explain why? It looks fine to me.
    string *s;
    s = (string *) "This is my house. I have to defend it.";
    cout << *s << endl;

A:

Indirecting through a pointer of type std::string* when it doesn't point to an object of type std::string has undefined behaviour.
A string literal is not an object of type std::string. String literal is an array of characters. std::string is a class defined in the header <string>.

Running this code produces a segmentation fault, but can someone explain why?

You indirect through a pointer that doesn't point to an object of compatible type. The behaviour of your program is undefined.

P.S. It is never necessary to use C-style cast (such as (type)expression). It can easily suppress helpful compilation errors and replace them with undefined behaviour. It should be avoided.
If you hadn't used a C-style cast here, then the type system would have alerted you to the mistake before getting to run the program. In this case, you might have seen an error message similar to:
error: cannot convert 'const char [39]' to 'std::string*' {aka 'std::basic_string<char>*'} in assignment

helping you realise that the types do not match.

