【问题标题】:pointer segfault problems指针段错误问题
【发布时间】:2011-03-18 08:30:20
【问题描述】:

指针段错误问题...

与此同时,我已经做了几个星期的 c++,但我又遇到了这个问题。

基本上我已经给出了这些课程。我不能改变它们。我从_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_

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

【问题讨论】:

    标签: c++ pointers segmentation-fault


    【解决方案1】:

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

    ns2__SOAPImportResult *return_; //in the class _ns3__importAuftragResponse 
    
    
    int *numberOfIgnoreds;  //in the class  ns2__SOAPImportResult
    

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

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

    【讨论】:

      【解决方案2】:

      这看起来像gsoap。在这种情况下,您必须使用 soap_malloc 分配您返回的内存。

      例如在FAQ页面上,你会发现这个例子:

      int ns__itoa(struct soap *soap, int i, char **a)
      { *a = (char*)soap_malloc(soap, 11);
        sprintf(*a, "%d", i);
        return SOAP_OK;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-13
        • 2020-07-04
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        相关资源
        最近更新 更多