1

I've been given this as a .H file for homework, and I'm tasked with creating the .C to go with it. It's really simple stuff, I'm sure I'm missing something small.

#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

In my constructor, when I try to set the value of the SharedCString's count to 1, I get a segmentation fault.

I was trying to pass it using:

   shared->count = 1;

I'm not sure why this doesn't work.

Classtronaut
  • 203
  • 4
  • 9
  • 1
    You haven't provided the code you have written for your constructor, so it's hard to say. But, have you allocated memory for `shared`? – Greg Hewgill Sep 26 '12 at 22:43
  • I figured since it was mentioned in the String.H that it was build at "SharedCString *shared;", did I miss something? – Classtronaut Sep 26 '12 at 22:45
  • 1
    Yes; the declaration just means that the pointer points *somewhere*, but doesn't automatically allocate any space for it. From the comments in the header file, the whole point of this exercise is to get you to understand what pointers mean and how they can make data representation more efficient. – Greg Hewgill Sep 26 '12 at 22:47

2 Answers2

2

If you get a segfault on the line

shared->count = 1;

then shared is NULL or is garbage, pointing to memory that your process does not own.

You should do

shared = new SharedCString;

before accessing it.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Thanks alot! I had my stuff set up this way earlier, but an error in one of my other classes had me second guessing myself, I've got it working now thanks! – Classtronaut Sep 26 '12 at 22:54
2

You have to allocate space in memory for SharedCString. It's a pointer right now, pointing to some random memory address (just like any uninitialized variable).

This question covers it: Dynamically allocate memory for struct

Community
  • 1
  • 1
Ben Richards
  • 528
  • 5
  • 14