我正在使用Visual Studio 2013.我收到Access violation reading location 0xCDCDCDD1
错误。来自Wikipedia: Magic Numbers,here和this question的引用告诉我,我使用的是未初始化的指针。我认为问题在于我正在使用的malloc
函数,尽管在使用之前我确实参考过CPlusPlus文档。
我的代码:
#include "SingleNode.h"
#include "SingleList.h"
#include <iostream>
SingleList::SingleList() {}
SingleList::~SingleList() {}
...
void SingleList::addHead(int value){
ISingleNode *temp1 = (ISingleNode *)malloc(sizeof(SingleList));
head = NULL;
temp1->setValue(value);
temp1->setNext(head->getNext());
if (!head->getNext())
{
head = temp1;
}
else
{
temp1->setNext(head->getNext());
head = temp1;
}
}
...
错误在第temp1->setValue(value);
行
此处包含setValue(int value)
功能:
#include "SingleNode.h"
SingleNode::SingleNode() {}
SingleNode::~SingleNode() {}
void SingleNode::setValue(int value){
this->value = value;
}
int SingleNode::getValue(){
return value;
}
ISingleNode * SingleNode::getNext(){
return next;
}
void SingleNode::setNext(ISingleNode * next){
this->next = next;
}
SingleNode.h:
#pragma once
#include "Interfaces01.h"
class SingleNode :public ISingleNode{
private:
int value;
ISingleNode * next = NULL;
public:
SingleNode();
~SingleNode();
void setValue(int value);
int getValue();
ISingleNode * getNext();
void setNext(ISingleNode * next);
};
SingleList.h:
#pragma once
#include "Interfaces01.h"
class SingleList :public ISingleList{
private:
int value;
ISingleNode * head=NULL;
ISingleNode * temp=NULL;
ISingleNode * next=NULL;
ISingleNode * temp1;
public:
SingleList();
~SingleList();
ISingleNode * getHead();
void setHead(ISingleNode * head);
void addHead(int value);
void orderSort2();
void orderSort3();
void sequenceOrderSort();
void reverse();
ISingleNode * swap(ISingleNode * head, int k);
ISingleNode * get_node(ISingleNode * head, int k);
};
在断行时,调试器显示以下值:
答案 0 :(得分:5)
变化:
ISingleNode *temp1 = (ISingleNode *)malloc(sizeof(SingleList));
成:
ISingleNode *temp1 = new SingleList;
您正在访问NULL
指针:
head = NULL; // set to NULL
temp1->setValue(value);
temp1->setNext(head->getNext()); // oops!
你可能意味着:
void SingleList::addHead(int value)
{
ISingleNode *temp1 = new SingleList;
temp1->setValue(value);
temp1->setNext(head);
head = temp1;
}