2013-06-24 61 views
1

我目前正在使用gsoap版本2.8实现webservice并运行到分段错误。将值赋给使用soap_malloc创建的std :: string指针

为此我使用soap_malloc这样的分配内存:

OSoap *myObject = (OSoap *)soap_new_OSoap(this); 
myObject->myString = (std::string*)soap_malloc(this, sizeof(std::string)); 

使用WSDL生成OSoap的源代码,看起来像这样:

class SOAP_CMAC OSoap { 
... 
public: 
    std::string *myString; // optional attribute 
... 
} 

现在我有一个字符串分配但如何我写内容给这个字符串?

myObject->myString->insert(0, "123"); 

*(myObject->myString) += "abc"; 

导致段故障。

std::string *abc = new std::string("abc"); 
myObject->myString = abc; 

工作,但产生内存泄漏,我尽量避免。

搜索谷歌或为计算器如何复制在C++字符串没有给我一个提示如何使用的std :: string指针

+0

我不知道gSoap,但是在我看来,您正在分配std :: string(在固定的内存分配中),然后插入/附加到字符串的内部内存。当你新建字符串时,你完全控制了对象,它可以工作(但泄漏) - 你可以试验固定大小的字符数组,然后看看soap_malloc是什么? (I.E.复制到数组中) – Caribou

+0

固定大小的char数组无效,因为我需要使用{}对它们进行实例化,char *确实有效。 –

+0

好的 - 我认为seg故障可能是由于字符串在内部重新分配内存引起的。希望这会让你更进一步。对不起,我无法提供更多帮助。 – Caribou

回答

3

确定要解决的问题 - 使用std ::时字符串*应使用soap_instantiate_std__string而不是在文档中找不到的soap_malloc,那么一切正常!

2

我有同样的问题。我看到你的std :: string *是一个“可选”属性。 之后,我写道:

<xsd:element minOccurs="1" maxOccurs="1" name="myString" type="xsd:string"/> 

它的头改变为std :: string! 我不知道你是否使用xsd元素,但这是一种很好的方式。

+0

在我的情况下,不允许更改xsd! –

0

复杂类型可以通过使用soap_new_XXX函数来实例化,如在这种情况下为soap_new_std__string(soap, 1)。该功能在内部调用soap_instantiate_std__string。内存将由gsoap自动释放。

请参阅gsoap documentation第9.13.1章内存分配和管理策略。