c++ - 传递值时出现段错误

标签 c++ struct segmentation-fault

我收到了一个 .H 文件作为家庭作业,我的任务是创建 .C 来配合它。这真的很简单,我确定我遗漏了一些小东西。

#ifndef String_H
#define String_H

#include <iostream>

class String
{
public:

  // constructor: initializes String with copy of 0-terminated C-string  
  String(const char *p);

  // destructor (when can shared data be released?)
  ~String();

  // copy constructor (how does this change reference counts?)
  String(const String &x);

  // assignment operator  (how does this change reference counts?)
  String &operator=(const String &x); 

  // return number of non-0 characters in string
  int size() const;

  // return reference count
  int ref_count() const;

  // returns pointer to character array
  const char *cstr() const;

private:

  // data containing character strings
  // shared by Strings when copying/assigning
  struct SharedCString
  {
    char *data; // 0-terminated char array
    int n;      // number of non-0 characters in string
    int count;  // reference count, how many Strings share this object?
  };

  SharedCString *shared;
};

#endif

在我的构造函数中,当我尝试将 SharedCString 的计数值设置为 1 时,出现了段错误。

我试图通过以下方式传递它:

   shared->count = 1;

我不确定为什么这不起作用。

最佳答案

如果在线上出现段错误

shared->count = 1;

然后 shared 为 NULL 或者是垃圾,指向您的进程不拥有的内存。

你应该这样做

shared = new SharedCString;

在访问它之前。

关于c++ - 传递值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611537/

相关文章:

c++ - 断然阻止或阻止带有特定参数的对象实例化

c - 二维数组结构出现段错误

无法弄清楚我是如何遇到段错误的

c++ - 为什么不调用子类方法?

c++ - Win32 控制台写入 (C/C++)

c++ - 用字符串指定 vector 的类型

c - 为什么 CGo 不能识别我在头文件中声明的结构?

post - 使用带有 map 数据的结构

c++ - 在没有测试数据的情况下查找段错误

opengl - 与 OpenGL、SDL 和图形驱动程序相关的内存泄漏和错误