分段传递值时出错

时间:2012-09-26 22:41:43

标签: 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的count的值设置为1时,我得到了一个分段错误。

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

   shared->count = 1;

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

2 个答案:

答案 0 :(得分:2)

如果您在线上获得了段错误

shared->count = 1;

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

你应该做

shared = new SharedCString;

访问之前。

答案 1 :(得分:2)

您必须在内存中为SharedCString分配空间。它现在是一个指针,指向一些随机存储器地址(就像任何未初始化的变量一样)。

这个问题涵盖了它:Dynamically allocate memory for struct