我一直在與我的任務之一,並在他們使用我malloc的導師工作。我的講師告訴我應該用新的。爲了在兩者之間轉換,我想確保我正確地做到了。從malloc過渡到新
我有什麼(幾個例子);
char* songTitle = (char*)malloc(sizeof(char)* 50);
songTitle = (char*)malloc(sizeof(char)* 50);
title = (char*)malloc(sizeof(char)* 50);
我希望在過渡時是正確的;
char* songTitle = new char[50];
songTitle = new char[50];
title = new char [50];
我正在使用的示例片段;
片段#1
cin.ignore();
cout << "What is the title of the song? " << endl;
char* songTitle = (char*)malloc(sizeof(char)* 50);
cin.getline(songTitle, 50);
songTitle[0] = std::toupper(songTitle[0]);
for (std::size_t i = 1; i < strlen(songTitle); ++i)
songTitle[i] = std::tolower(songTitle[i]);
片段#2
cin.ignore();
cout << "What is the title of the song? " << endl;
songTitle = (char*)malloc(sizeof(char)* 50);
cin.getline(songTitle, 50);
songTitle[0] = std::toupper(songTitle[0]);
片段#3
while (true && count < ARRAY_SIZE)
{
title = (char*)malloc(sizeof(char)* 50);
artist = (char*)malloc(sizeof(char)* 50);
duration = (char*)malloc(sizeof(char)* 50);
album = (char*)malloc(sizeof(char)* 50);
inFile.getline(title, 50, '\|');
songs[count].setTitle(title);
inFile.getline(artist, 50, '\|');
songs[count].setArtist(artist);
inFile.getline(duration, 50, '\|');
songs[count].setDuration(duration);
inFile.getline(album, 50, '\|');
songs[count].setAlbum(album);
if (inFile.eof() == true)
break;
count++;
}
假設所有變量的類型都是char *並且您添加了分號,那麼看起來是正確的。 – Adam
真的,你應該直接轉換爲使用'std :: string',而不是''用'new'來使用'char *'。這幾乎可以自動解決你的內存泄漏問題 - 好吧,如果你有點小心。使用'new'是低級編程的事情,通常要避免。假設'songTitle'的初始化沒有被分配到'songTitle',那麼你或多或少是正確的,雖然漏了。你需要確定內存在哪裏釋放。如果在兩個操作之間沒有'delete [] songTitle;'',則初始化和賦值確定會泄漏內存。 –
'if(inFile.eof()== true)'應該是'if(!inFile)' –