如何在不导致内存泄漏的情况下将数组分配给结构内的指针

how to assign an array to a pointer inside a structure without causing memory leakage

本文关键字:分配 数组 结构 指针 情况下 泄漏 内存      更新时间:2023-10-16

我正在从函数中的文件中读取数据并将数据保存到临时数组中。然后,我将数组传递给结构内的指针。但是当我检查 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]='';
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;
}

首先,在您的情况下,您应该使用旧的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 这个 aproach 更好:

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

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