我的代码出现内存增长问题,求排查原因(附表格操作代码)
Let’s break down the likely causes of your memory growth issue, focusing on the code snippets you provided:
1. QTableWidgetItem Memory Leaks (Most Likely Culprit)
Your clearTable method uses clearContents() followed by setRowCount(0), but this combination can leave QTableWidgetItem objects hanging in memory:
clearContents()removes items from the table’s cells but does not delete them—it just detaches them from the table, meaning the table no longer takes ownership of those items.- When you call
setRowCount(0)afterward, it removes the empty rows, but since the items were already detached byclearContents(), they’re never deleted. This creates persistent memory leaks every time you clear the table.
Fix for clearTable:
Instead of using clearContents(), use setRowCount(0) directly (which will delete all items owned by the table if you added them via setItem):
void AudioAPI::clearTable(QTableWidget *songTable) { // This single call removes all rows AND deletes the items (since the table owns them) songTable->setRowCount(0); }
If you need to keep rows but clear contents, delete each item explicitly:
void AudioAPI::clearTable(QTableWidget *songTable) { for (int row = 0; row < songTable->rowCount(); ++row) { for (int col = 0; col < songTable->columnCount(); ++col) { delete songTable->takeItem(row, col); } } // Optional: Remove rows if needed songTable->setRowCount(0); }
2. TagLib Resource Management Checks
Your TagLib usage looks mostly safe (using TagLib::FileRef, a smart pointer), but verify these edge cases:
- Don’t store pointers to
file.tag()orfile.audioProperties()outside the scope ofcreateSongFromPath—these pointers are owned by theFileRefand become invalid oncefilegoes out of scope. - Add null checks for
file.tag()before accessing methods liketitle()orartist()(corrupted files might return a null tag, leading to undefined behavior, though this is less likely to cause steady memory growth).
3. Unfinished Code in createSongFromPath
Your snippet cuts off at new QTableWidgetItem...—if you’re creating additional objects with new that aren’t assigned to the table (which takes ownership), those objects will leak. Double-check any custom objects or dynamically allocated data in this method to ensure they’re properly deleted.
Quick Testing Tip
Use Qt’s built-in memory tools (like valgrind on Linux/macOS or the Memory Analyzer in Qt Creator) to track exactly which objects are leaking. This will confirm if leaks come from QTableWidgetItem instances or other parts of your code.
内容的提问来源于stack exchange,提问作者Tung

