当我尝试将字符串值分配给结构的成员时,我的程序崩溃了。 我怀疑结构中的成员(字符串类型)从未在内存中正确分配。
以下是我的参考代码:
#include <string>
#include <sstream>
struct DataRow
{
std::string result;
float temp;
struct DataRow* next;
};
int main( )
{
DataRow* node = (DataRow*)malloc(sizeof(DataRow)); // Allocation of memory for struct here
int currentLoc = 0;
std::string dataLine = "HUUI 16:35:58 54.4 25.1 PDJ 1 MEME PPP PS$% sc3 BoomBoom SuperPower P0 123 25.86 0 11.1 1.0 50.0 W [2.0,0.28] 1.15 [5,6,100]";
std::string dataWord;
std::stringstream sDataLine( dataLine );
while ( sDataLine >> dataWord )
{
if( currentLoc == 0 )
{ node->result = dataWord; } // <-- Problem occurs here
else if ( currentLoc == 3 )
{ node->temp = atof(dataWord.c_str()); } // <-- This code works no problem on it's own
else
{ }
currentLoc++;
}
return 0;
}
代码在node->result = dataWord
处失败。但是如果我注释掉这个if语句,只留下node->temp=atof(dataWord.c_str());
代码没有问题。
如何为DataRow结构的字符串成员实现正确的内存分配?
答案 0 :(得分:7)
malloc
无法确保调用struct
成员的任何构造函数。在C ++ struct
与class
基本相同,唯一的区别是成员默认为public
而不是private
。因此,您应该new
对象/结构,并在完成后delete
。
答案 1 :(得分:6)
分配node
的方式不正确:如果要在C ++中动态分配非POD类型,则需要使用new
,因为它将调用所需的构造函数(后跟一个在适当的时候致电delete
。
但是分配自动实例可能更简单:
DataRow node;
如果确实需要指针,请务必查看smart pointers,尤其是std::unique_ptr
和std::shared_ptr
。另请参阅boost::scoped_ptr
。
答案 2 :(得分:4)
在C ++中使用'new'而不是'malloc'。使用malloc不会运行类的构造函数,因此不会初始化字符串。
答案 3 :(得分:3)
你必须创建一个新结构,而不是使用malloc。
所以使用:
DataRow* node = new DataRow;
你也应该像这样清理它:
delete node;
如果你不想从堆中分配它,你也可以这样做:
DataRow node;
答案 4 :(得分:0)
所以在我回答你的问题之前,我只是想说你不应该在c ++中使用Malloc,除非你被迫。这个答案很好地解释了为什么。
In what cases do I use malloc vs new?
随着说改变这一行
DataRow* node = (DataRow*)malloc(sizeof(DataRow));
到此
DataRow* node = new DataRow;
将解决您的问题