【发布时间】:2017-06-12 03:19:06
【问题描述】:
我正在编写一个函数,它从 csv 文件中读取各种属性,包括字符串,并将其分配给恰好位于类似结构数组中的结构的相关元素。
每当我尝试将值分配给:
materialLookup[v-1].name
程序崩溃。
MaterialL
是一个带有string 元素的结构,称为name,如下所示:
struct MaterialL {
string name;
double sigma;
double corLength;
double mu;
double muPrime;
double ep;
double epPrime;
};
我检查了我是否正确地从 csv 文件中读取了string,在这种情况下,它是“Drywall”。在我能够在下一行 cout<<"hey"; 之前,该程序总是崩溃。我唯一的想法是,因为程序在我分配它之前不知道string 的大小,所以它不会为它留下任何内存。如果是这样,我该如何纠正?
unsigned int getMatLookUp(string filename)
{
int nLines = getNumOfLines(filename);
cout << nLines;
materialLookup = (MaterialL*)alignedMalloc(nLines * sizeof(MaterialL));
ifstream file(filename);
int v = 0;
string value;
if (file.is_open() && fileExists(filename))
{
//flush title line
for (int p = 0; p < 6; p++){ std::getline(file, value, ','); }std::getline(file, value);
v++;
//get all the materials
while (v < nLines -1)
{
std::getline(file, value, ',');
cout << value<<"\n\n";
materialLookup[v - 1].name = value;
cout << "hey";
std::getline(file, value, ',');
cout << value << "\n\n";
materialLookup[v - 1].sigma = stod(value);
std::getline(file, value, ',');
materialLookup[v - 1].corLength = stod(value);
std::getline(file, value, ',');
materialLookup[v - 1].mu = stod(value);
std::getline(file, value, ',');
materialLookup[v - 1].muPrime = stod(value);
std::getline(file, value, ',');
materialLookup[v - 1].ep = stod(value);
std::getline(file, value);
materialLookup[v - 1].epPrime = stod(value);
v++;
}
file.close();
}
else
{
cout << "Unable to open file when loading material lookup in function getMatLookUp press enter to continue\n";
cin.get();
}
return(0);
}
【问题讨论】:
-
你为什么不使用
new,或者更好的是std::vector? -
@NathanOliver,可能是因为对齐,尽管可以使用自定义分配器或在 C++17 中添加对齐参数的
new的新重载。 -
@chris
new不会返回正确对齐的内存吗? -
使用
std::vector。如果有理由使用alignedMalloc(),他应该解释为什么他在问题中使用它而不是std::vector。 -
@NathanOliver,我想是的(尽管 cppreference 指的是我在 N4527 中看不到的一些
__STDCPP_DEFAULT_NEW_ALIGNMENT__,可能是时候更新了)。不过,也许 OP 正在寻找过度对齐的内存。我真的不知道,反正对齐经验也很少。