Skip to content

Commit a75bf7f

Browse files
committed
fixes #187 - out-of-range InsertColumn to throw exception instead of segfaulting
1 parent 98ae940 commit a75bf7f

3 files changed

Lines changed: 56 additions & 2 deletions

File tree

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ if(RAPIDCSV_BUILD_TESTS)
183183
add_unit_test(test097)
184184
add_unit_test(test098)
185185
add_unit_test(test099)
186+
add_unit_test(test100)
186187

187188
# perf tests
188189
add_perf_test(ptest001)

src/rapidcsv.h

Lines changed: 13 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.86
5+
* Version: 8.87
66
*
77
* Copyright (C) 2017-2025 Kristofer Berggren
88
* All rights reserved.
@@ -852,7 +852,18 @@ namespace rapidcsv
852852
if (std::distance(mData.begin(), itRow) >= mLabelParams.mColumnNameIdx)
853853
{
854854
const size_t rowIdx = static_cast<size_t>(std::distance(mData.begin(), itRow));
855-
itRow->insert(itRow->begin() + static_cast<int>(dataColumnIdx), column.at(rowIdx));
855+
if (dataColumnIdx <= itRow->size())
856+
{
857+
itRow->insert(itRow->begin() + static_cast<int>(dataColumnIdx), column.at(rowIdx));
858+
}
859+
else
860+
{
861+
const std::string errStr = "column out of range: " +
862+
std::to_string(pColumnIdx) + " (on row " +
863+
std::to_string(std::distance(mData.begin(), itRow)) +
864+
")";
865+
throw std::out_of_range(errStr);
866+
}
856867
}
857868
}
858869

tests/test100.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// test100.cpp - exception message inserting column out-of-range
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\n"
12+
"1,3,9\n"
13+
"2,4,16\n"
14+
;
15+
16+
std::string path = unittest::TempPath();
17+
unittest::WriteFile(path, csv);
18+
19+
try
20+
{
21+
rapidcsv::Document doc(path);
22+
23+
// insert at end (append)
24+
doc.InsertColumn(3, std::vector<int>({ 1, 2 }), "D");
25+
26+
// insert at end (append)
27+
doc.InsertColumn(4, std::vector<int>({ 3, 4 }), "E");
28+
29+
// insert out-of-range
30+
ExpectExceptionMsg(doc.InsertColumn(6, std::vector<int>({ 5, 6 }), "F"),
31+
std::out_of_range, "column out of range: 6 (on row 0)");
32+
}
33+
catch (const std::exception& ex)
34+
{
35+
std::cout << ex.what() << std::endl;
36+
rv = 1;
37+
}
38+
39+
unittest::DeleteFile(path);
40+
41+
return rv;
42+
}

0 commit comments

Comments
 (0)