2

当我尝试将字符串值分配给结构的成员时,我的程序崩溃了。我怀疑结构中的成员(字符串类型)从未在内存中正确分配。

这是我的参考代码:

#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 结构的字符串成员实现正确的内存分配?

4

5 回答 5

7

malloc不确保您的成员的任何构造函数struct被调用。在 C++struct中与 基本相同class,唯一的区别是成员public默认是而不是private. 所以你应该new对象/结构,并delete在完成后。

于 2013-06-11T18:47:40.193 回答
6

您分配的方式node不正确:如果您想在 C++ 中动态分配非 POD 类型,则需要使用new,因为它将调用所需的构造函数(然后delete在适当时调用 to)。

但是分配一个自动实例可能更简单:

DataRow node;

如果您确实需要指针,请务必查看智能指针,尤其是std::unique_ptrstd::shared_ptr。另请参阅boost::scoped_ptr

于 2013-06-11T18:47:46.737 回答
4

在 C++ 中使用“new”而不是“malloc”。使用 malloc 不会运行您的类的构造函数,因此不会初始化字符串。

于 2013-06-11T18:49:00.340 回答
3

您必须创建一个新结构并且根本不使用 malloc。

所以使用:

DataRow* node = new DataRow;

您还应该像这样清理它:

delete node;

如果您不想从堆中分配它,您也可以这样做:

DataRow node;
于 2013-06-11T18:47:50.127 回答
0

所以在我回答你的问题之前,我只想说你不应该在 c++ 中使用 Malloc,除非你被迫这样做。这个答案很好地解释了为什么。

在什么情况下我使用 malloc 与 new?

话虽如此,改变这条线

DataRow* node = (DataRow*)malloc(sizeof(DataRow));

对此

DataRow* node = new DataRow;

会解决你的问题

于 2013-06-11T18:56:48.297 回答