2011-03-18 70 views
1

指针段错误问题...指针段错误问题

我一直在做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; 

我大多得到分段错误我通常知道在运行时会发生什么但不能拿出正确的颂歌。请帮忙。

编辑

取得进展THX你的答案,谢里夫,但仍需要一些理解

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

什么我很难明白的是,如何或为何的东西是已经分配内存“有”,因为有对象kout的成员return_0

那么说我需要为我分配给它的变量(它是相同类型的过程)分配内存是正确的吗?

回答

2

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

ns2__SOAPImportResult *return_; //in the class _ns3__importAuftragResponse 


int *numberOfIgnoreds; //in the class ns2__SOAPImportResult 

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

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

1

这看起来像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; 
}