[英]read access violation error
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. 它说访问冲突读取位置0xcccccccc。 The class must allocate the memory fore adjacent, but I think it didn't how can I solve this problem?
该类必须在相邻的位置分配内存,但是我认为这不能解决这个问题吗?
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. 您正在复制
adjNum+1
元素,即使(我假设) adjacent
元素仅包含adjNum
元素。 Remove the +1
from the for
loop. 从
for
循环中删除+1
。
Besides the issues strager mentioned, you might be missing initialization for adjacent
, eg like this: 除了上面提到的问题之外,您可能还没有为
adjacent
初始化,例如:
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. 注意
unsigned
参数,在这种情况下,负adj_num
最有可能是没有意义的。
If you don't initialize adjacent
, it contains some garbage value and dereferencing it or passing it to delete[]
leads to undefined behaviour. 如果您不初始化
adjacent
,则它包含一些垃圾值,将其取消引用或将其传递给delete[]
会导致不确定的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.