C++ 读访问冲突C++;
下面的代码编译。但是,当我在调试模式下执行时,我在下面注释标记的位置遇到读取访问冲突:C++ 读访问冲突C++;,c++,memory-leaks,C++,Memory Leaks,下面的代码编译。但是,当我在调试模式下执行时,我在下面注释标记的位置遇到读取访问冲突: #include <iostream> #include <vector> using namespace std; struct information { int32_t bytes; std::string packet_header; }; class updateClassList { public: std::vector<inform
#include <iostream>
#include <vector>
using namespace std;
struct information
{
int32_t bytes;
std::string packet_header;
};
class updateClassList
{
public:
std::vector<information*> vecptr;
void updateClassListN()
{
cout << "inside constructor";
for (int32_t i = 0;i < 2;i++)
{
information* ptr = new information();
ptr->bytes = i;
ptr->packet_header = "Heavy";
vecptr.push_back(ptr); // READ ACCESS VIOLATION
}
}//endctr
};
class updateClass
{
public:
int32_t bytes;
std::string packet_header;
updateClass** item;
};
updateClass* GetObjectbyHandle(int32_t handle)
{
updateClass* tmpObj=NULL;
updateClassList* tmpObjList=NULL;
tmpObjList->updateClassListN();
tmpObj->bytes = tmpObjList->vecptr.at(handle)->bytes;
tmpObj->packet_header = tmpObjList->vecptr.at(handle)->packet_header;
return tmpObj;
}
bool updater(information* tmpPtr, int32_t handle)
{
cout << "in updater function";
updateClass* obj = GetObjectbyHandle(handle);
if (obj == NULL) return false;
tmpPtr->bytes = obj->bytes;
tmpPtr->packet_header = obj->packet_header;
cout << tmpPtr->packet_header;
return true;
}
int main()
{
int32_t handle = 0;
information n;
cout << "in main";
bool b = updater(&n, handle);
std::cout << "Decoder Status: " << b;
return 0;
}
#包括
#包括
使用名称空间std;
结构信息
{
int32_t字节;
std::字符串包_头;
};
类updateClassList
{
公众:
std::vectorvecptr;
void updateClassListN()
{
cout字节=i;
ptr->packet_header=“Heavy”;
vecptr.push_back(ptr);//读取访问冲突
}
}//endctr
};
类更新类
{
公众:
int32_t字节;
std::字符串包_头;
更新类**项;
};
updateClass*GetObjectbyHandle(int32\u t handle)
{
updateClass*tmpObj=NULL;
updateClassList*tmpObjList=NULL;
tmpObjList->updateClassListN();
tmpObj->bytes=tmpObjList->vecptr.at(handle)->字节;
tmpObj->packet\u header=tmpObjList->vecptr.at(handle)->packet\u header;
返回tmpObj;
}
bool更新程序(信息*tmpPtr,int32\u t句柄)
{
cout bytes=obj->bytes;
tmpPtr->packet\u header=obj->packet\u header;
cout分组头;
返回true;
}
int main()
{
int32_t handle=0;
信息n;
无法对您在上面分配了一行的空指针进行GetObjectbyHandle调用updateClassListN
。您预期会发生什么?此常见问题称为“指针的无用使用”。所示代码中大约90%的指针使用没有完成任何任务,只会使事情变得更加复杂和容易出错。@SamVarshavchik上述程序的目的不是展示一个好的代码。而是提出我正在处理的另一个项目中描述泄漏的代码模板。