Skip to content

Commit 609c17d

Browse files
committed
Improve safety and correctness of drag-and-drop file loading, use vector instead of manual memory management
1 parent 353a8d8 commit 609c17d

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

src/System/System.cpp

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include <ctime>
3535
#include <bitset>
3636
#include <list>
37+
#include <vector>
3738

3839
#undef DELETE
3940

@@ -712,23 +713,29 @@ bool handleMsg(UINT msg, WPARAM wp, LPARAM lp, LRESULT& result)
712713
{
713714
POINT pos;
714715
DragQueryPoint((HDROP)wp, &pos);
715-
// Passing 0xFFFFFFFF will return the file count.
716-
int numFiles = (int)DragQueryFileW((HDROP)wp, 0xFFFFFFFF, 0, 0);
717-
char** files = (char**)malloc(sizeof(char*) * numFiles);
718-
for(int i = 0; i < numFiles; ++i)
716+
717+
// Get the number of files dropped.
718+
UINT numFiles = DragQueryFileW((HDROP)wp, 0xFFFFFFFF, nullptr, 0);
719+
std::vector<String> files(numFiles);
720+
721+
for (UINT i = 0; i < numFiles; ++i)
719722
{
720-
// Giving 0 for the stringbuffer returns path size without nullbyte.
721-
int pathlen = (int)DragQueryFileW((HDROP)wp, i, 0, 0);
722-
WideString wstr(pathlen, 0);
723-
DragQueryFileW((HDROP)wp, i, wstr.begin(), pathlen + 1);
724-
String str = Narrow(wstr);
725-
files[i] = (char*)malloc(str.len() + 1);
726-
memcpy(files[i], str.begin(), str.len() + 1);
723+
// Get the length of the file path and retrieve it.
724+
UINT pathLen = DragQueryFileW((HDROP)wp, i, nullptr, 0);
725+
WideString wstr(pathLen, 0);
726+
DragQueryFileW((HDROP)wp, i, wstr.begin(), pathLen + 1);
727+
files[i] = Narrow(wstr);
727728
}
729+
728730
DragFinish((HDROP)wp);
729-
myEvents.addFileDrop(files, numFiles, pos.x, pos.y);
730-
for(int i = 0; i < numFiles; ++i) free(files[i]);
731-
free(files);
731+
732+
// Pass the file drop event to the input handler.
733+
std::vector<const char*> filePtrs;
734+
for (const auto& file : files)
735+
{
736+
filePtrs.push_back(file.str());
737+
}
738+
myEvents.addFileDrop(filePtrs.data(), static_cast<int>(filePtrs.size()), pos.x, pos.y);
732739
}
733740
break;
734741
}

0 commit comments

Comments
 (0)