我有下面的代码。它编译得很好,但它向我展示了字符串是"E#^$$@$$$$$$$“。知道为什么吗?
ifstream InFile(Filename);
if (!InFile)
return false;
std::string Name;
Song *pSong;
for (int a = 0; a < Playlist.size(); a++)
{
delete Playlist[a];
}
Playlist.clear();
while (true)
{
if (!InFile)
break;
pSong = new Song();
std::getline(InFile, Name, '\n');
pSong->File = const_cast<char*>(Name.c_str());
std::getline(InFile, Name, '\n');
pSong->Volume = atof(Name.c_str());
Playlist.push_back(pSong);
}播放列表:std::vector<Song*>Playlist;
发布于 2014-05-02 19:48:14
这是有问题的台词。
pSong->File = const_cast<char*>(Name.c_str());在从文件中读取下一行文本后,您正在存储一个指向无效内存的指针。
改为:
pSong->File = strdup(Name.c_str());如果您的平台没有strdup,下面是一个简单的实现。
char* strdup(char const* s)
{
char* ret = malloc(strlen(s)+1);
strcpy(ret, s);
return ret;
}警告,因为您在使用strdup时分配内存,因此必须确保将其释放。
您可以选择使用new分配内存,因为您使用的是C++。如果使用new分配内存,则必须使用delete来释放内存。如果您使用malloc来分配内存,如这个答案所示,您必须使用free来释放内存。
https://stackoverflow.com/questions/23435771
复制相似问题