c++ - 指针段错误问题

标签 c++ pointers segmentation-fault

指针段错误问题...

同时,我已经用了几个星期的 c++,但我又遇到了那个问题。

基本上我已经给出了这些类(class)。我不能改变他们。我从 _ns3__importAuftragResponse kout;

的实例开始
class SOAP_CMAC _ns3__importAuftragResponse
{
public:
        ns2__SOAPImportResult *return_;
         ...




class SOAP_CMAC ns2__SOAPImportResult
{
public:
        bool *error;   
        int *numberOfIgnoreds; 
        ....

我的代码需要检查 numberOfIgnoreds

第一种方法

ns2__SOAPImportResult* imp_result;
imp_result = kout.return_;

int num;
num = *imp_result->numberOfIgnoreds;

或者我用

ns2__SOAPImportResult imp_result;
imp_result = *(kout.return_);
int* num;
*num = *imp_result.numberOfIgnoreds;

我主要遇到段错误 我通常知道运行时会发生什么,但无法想出正确的颂歌。请帮忙。

编辑

感谢您的回答,Nawaz,但仍需要一些理解

ns2__SOAPImportResult * imp_ptr = new ns2__SOAPImportResult;
imp_ptr = kout.return_;
int * num = new (int);
// next line segfaults
*num = *imp_ptr->numberOfIgnoreds;

让我难以理解的是,如何或为什么为已经“存在”的东西分配内存,因为存在对象 kout 的成员 return_

那么说我需要为分配给它的变量(当然是同一类型)分配内存是否正确?

最佳答案

您很可能没有为您在引用的代码中使用的以下成员分配内存。

ns2__SOAPImportResult *return_; //in the class _ns3__importAuftragResponse 


int *numberOfIgnoreds;  //in the class  ns2__SOAPImportResult

除此之外,我看不到任何可能出错的地方!

确保为这些成员(以及程序中的所有其他指针)分配内存在使用它们之前。您可以使用 new 来分配内存。或者,您也可以使用 malloc()。无论您使用什么,都要始终如一地使用它,并在完成后释放内存,分别使用 deletefree()!

关于c++ - 指针段错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5349599/

相关文章:

c++ - 创建用户定义类的实例并打开文件后出现 memset 问题

c++ - 对象指针的指针取消引用?

C数组/指针问题

c - 如何编写段错误处理程序,以便不重新启动错误指令? (C 和 Linux)

c++ - 使用运算符 [] 时的 std::map 段错误

c - 家庭作业的段错误。不知道为什么

c++ - 尝试使用 libgit2 快进时出现 "cannot set OID on symbolic reference"

c++ - 抽象类和虚方法问题 : cannot declare variable ‘list’ to be of abstract type ‘aStack<int>’ aStack<int> list(5)

c# - 进程间通信 - C# 和 C++。访问路径被拒绝

C++ Struct within Struct + deleted function 错误