0
class Node{
      private:
              string name;
              Node** adjacent;
              int adjNum;
      public:
             Node();
             Node(string, int adj_num);
             Node(const Node &);
             bool addAdjacent(const Node &);
             Node** getAdjacents();
             string getName();
             ~Node();
      };

bool Node::addAdjacent(const Node &anode){
     Node** temp;   
     temp= new Node*[adjNum+1];
     for(int i=0;i<adjNum+1;i++)
         temp[i]=adjacent[i];
     temp[adjNum]=const_cast<Node *>(&anode);
     delete[] adjacent;
     adjacent=new Node*[adjNum+1];
     adjacent=temp;
     delete[] temp;
     adjNum++;
     return true;
}

int main()
{
    Node node1("A",0);
    Node node2("B",0);
    node1.getName();
    node1.addAdjacent(node2);
    system("PAUSE");
    return 0;
}

when the program comes to this part:

for(int i=0;i<adjNum+1;i++)
     temp[i]=adjacent[i];

it says Access violation reading location 0xcccccccc. The class must allocate the memory fore adjacent, but I think it didn't how can I solve this problem?

3
  • 1
    And the question is?....
    – Klaim
    Mar 14, 2010 at 21:05
  • I assume you are not allocating adjacent?
    – tyranid
    Mar 14, 2010 at 21:06
  • Try running the program through valgrind or a debugger.
    – strager
    Mar 14, 2010 at 21:06

2 Answers 2

3
 adjacent=new Node*[adjNum+1];
 adjacent=temp;
 delete[] temp;

This looks like a bug. You probably meant to write:

adjacent = temp;

and that's it.

Also, I think the problem lies with

for(int i=0;i<adjNum+1;i++)

You're copying adjNum+1 elements, even though (I assume) adjacent only contains adjNum elements. Remove the +1 from the for loop.

1
  • it's true I edited that part but also there is a memory allocation problem too as I mentioned up in the question. when creating the node1 object, I think it must create the pointer adjacent and allocate memory for it, but it just doesn't. The same error continues.
    – dbtek
    Mar 14, 2010 at 21:41
1

Besides the issues strager mentioned, you might be missing initialization for adjacent, e.g. like this:

Node::Node(std::string name, unsigned adj_num) 
  : name(name)
  , adjacent((adj_num > 0) ? new Node*[adj_num] : 0)
  , adjNum(adj_num)
{}

Note the unsigned parameter, a negative adj_num is most likely meaningless in this context.

If you don't initialize adjacent, it contains some garbage value and dereferencing it or passing it to delete[] leads to undefined behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.