2011-03-18 134 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; 
}