Skip to content

Commit 03133b5

Browse files
committed
fixes #194 - out-of-range RemoveRow to throw exception instead of segfaulting
1 parent 8b70667 commit 03133b5

File tree

3 files changed

+59
-2
lines changed

3 files changed

+59
-2
lines changed

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ if(RAPIDCSV_BUILD_TESTS)
187187
if(HAS_CODECVT)
188188
add_unit_test(test101)
189189
endif()
190+
add_unit_test(test102)
190191

191192
# perf tests
192193
add_perf_test(ptest001)

src/rapidcsv.h

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* rapidcsv.h
33
*
44
* URL: https://github.com/d99kris/rapidcsv
5-
* Version: 8.89
5+
* Version: 8.90
66
*
77
* Copyright (C) 2017-2025 Kristofer Berggren
88
* All rights reserved.
@@ -1045,7 +1045,17 @@ namespace rapidcsv
10451045
void RemoveRow(const size_t pRowIdx)
10461046
{
10471047
const size_t dataRowIdx = GetDataRowIndex(pRowIdx);
1048-
mData.erase(mData.begin() + static_cast<int>(dataRowIdx));
1048+
if (dataRowIdx < mData.size())
1049+
{
1050+
mData.erase(mData.begin() + static_cast<int>(dataRowIdx));
1051+
}
1052+
else
1053+
{
1054+
const std::string errStr = "row out of range: " +
1055+
std::to_string(pRowIdx);
1056+
throw std::out_of_range(errStr);
1057+
}
1058+
10491059
UpdateRowNames();
10501060
}
10511061

tests/test102.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// test102.cpp - exception message removing out-of-range row
2+
3+
#include <rapidcsv.h>
4+
#include "unittest.h"
5+
6+
int main()
7+
{
8+
int rv = 0;
9+
10+
std::string csv =
11+
"-,A,B,C,D\n"
12+
"1,3,9,81,6561\n"
13+
"2,4,16,256\n"
14+
"3,9,81,6561\n"
15+
;
16+
17+
std::string path = unittest::TempPath();
18+
unittest::WriteFile(path, csv);
19+
20+
try
21+
{
22+
rapidcsv::Document doc(path, rapidcsv::LabelParams(0, 0));
23+
24+
doc.RemoveRow("1");
25+
unittest::ExpectEqual(std::string, doc.GetRowName(0), "2");
26+
27+
doc.RemoveRow("3");
28+
unittest::ExpectEqual(std::string, doc.GetRowName(0), "2");
29+
30+
// doc has row 2 (0) now, thus 1 is out of range.
31+
ExpectExceptionMsg(doc.RemoveRow(1), std::out_of_range,
32+
"row out of range: 1");
33+
34+
ExpectExceptionMsg(doc.RemoveRow("1"), std::out_of_range,
35+
"row not found: 1");
36+
}
37+
catch (const std::exception& ex)
38+
{
39+
std::cout << ex.what() << std::endl;
40+
rv = 1;
41+
}
42+
43+
unittest::DeleteFile(path);
44+
45+
return rv;
46+
}

0 commit comments

Comments
 (0)