为什么设置 const char* 会导致分段错误?

Why does setting const char* gives segmentation fault?

我有这个简单的功能

 struct MyException : public exception
{
    const char *errorMessage = NULL;

    void SetMessage(const char* message)
    {
        errorMessage = message;
    }

  const char * what () const throw ()
  {
    return errorMessage;
  }
};
struct MyException *socketException;

当我打电话给

socketException->SetMessage("socket connection error");
       throw *socketException;

我在将消息设置为 errorMessage 的那一行遇到了分段错误。我遗漏了一些非常基本的东西,但我无法弄清楚。我检查了有关分段错误的其他问题,我知道它有时与指针的误用有关。但是我还是不明白。

您从未创建 class MyException 的实例,因此当您尝试调用 SetMessage 时,您没有可调用它的对象。

改为这样做:

struct MyException socketException;

...

socketException.SetMessage("socket connection error");
       throw socketException;