如何将数组分配给结构内的指针而不会导致内存泄漏

时间:2018-04-14 16:09:11

标签: c++

我正在从函数中的文件中读取数据并将数据保存到临时数组中。然后我将数组传递给结构内的指针。但是当我检查main函数中的输出时,我正在读取的数据受到损害,并且某些值存在内存泄漏。 我想知道如何在不导致内存泄漏的情况下读取main函数中的数据。

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>

using namespace std;

struct myWeather
{
    wchar_t *cityName;
    float *temperature, *pressure, *direction, *wind;
    myWeather *next, *prev;
};

myWeather *readData();

int main()
{
    myWeather *location, *currLoc;

    location = readData();
    currLoc = location;

    for(int c=0; c<49; c++)
   {
        cout<< "temp value"<< c+1<<": "<< (*currLoc->temperature+c)<<endl;
   }

    for(int f=0; f<1441; f++)
    {
    cout<< "pressure value"<< f+1<<": "<< *(currLoc->pressure+f)<<endl;
    }

    for(int g=0; g<720; g++)
    {
        cout<< "Dir value"<< g+1<<": "<< *(currLoc->direction+g)<<endl;
    }

    for(int h=0; h<720; h++)
    {
        cout<< "Wind value"<< h+1<<": "<< *(currLoc->wind+h)<<endl;
    }

    return 0;
}

myWeather *readData()
{
    myWeather *headPTR;
    char cityText[80];
    wchar_t cityNym[80];
    string myCity;
    float tmpData[49], prsData[1441], winData[720], dirData[720];
    int len;

    ifstream weatherFile ("Data.txt", ios::in);

    headPTR = new myWeather;
    getline(weatherFile, myCity);
    len= myCity.length();
    myCity.copy(cityText, len, 0);
    cityText[len]='\0';
    mbstowcs(cityNym, cityText, strlen(cityText)+1);
    headPTR->cityName = new wchar_t;
    headPTR->cityName= cityNym;
    weatherFile>> cityText;
    weatherFile>>len;

    for(int a=0; a<49; a++)
    {
        weatherFile>>tmpData[a];
    }
    headPTR->temperature = new float;
    headPTR->temperature = tmpData;

    weatherFile>> cityText;
    weatherFile>>len;
    for(int b=0; b<1441;b++)
    {
        weatherFile>>prsData[b];
    }

    headPTR->pressure= new float;
    headPTR->pressure= prsData;

    weatherFile>> cityText;
    weatherFile>>len;
    for(int d=0; d<720; d++)
    {
        weatherFile>>dirData[d];
    }
    headPTR->wind= new float;
    headPTR->wind= dirData;

    weatherFile>> cityText;
    weatherFile>>len;
    for(int e=0; e<720; e++)
    {
        weatherFile>>winData[e];
    }
    headPTR->direction = new float;
    headPTR->direction = winData;

    weatherFile.close();

    return headPTR;
}

1 个答案:

答案 0 :(得分:0)

首先,在您的情况下使用数组,您应该使用旧std::vector<float>wstring(对于cityName)。这正是您所需要的。

如果是nextprevious,您可以将std::unique_ptr用于next,将原始指针用于previous

基本上它可能看起来像这样:

struct myWeather
{
    std::wstring cityName;
    std::vector<float> temperature, pressure, direction, wind;
    std::unique_ptr<myWeather> next;
    myWeather prev;
};

但另一方面,看起来你正在实现已经提供的双链接列表,所以IMO这个方法更好:

struct myWeather
{
    std::wstring cityName;
    std::vector<float> temperature, pressure, direction, wind;
};

using WeatherRecords = std::list<myWeather>;

所以实际上你不需要任何花哨的指针或使用new delete运算符。