Skip to content

Commit 7569694

Browse files
committed
parseRow() memory leak fix
1 parent 2033866 commit 7569694

2 files changed

Lines changed: 21 additions & 3 deletions

File tree

CSV_Parser.cpp

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,12 +116,30 @@ char __attribute__((weak)) feedRowParser() { return '-'; }
116116
extern bool __attribute__((weak)) rowParserFinished();
117117
bool __attribute__((weak)) rowParserFinished() { return true; }
118118
// both functions above must be defined by the user, weak attribute is to avoid compilation
119-
// fail if the user doesn't define them
119+
// fail if the user doesn't define them (because not every user will use parseRow() method)
120120

121121
bool CSV_Parser::parseRow() {
122+
// parseRow() should never be used together with the original way of parsing csv
123+
// (by "original way of parsing" I mean: by using "cp <<" operator or by supplying whole csv at once)
124+
// parseRow() requires feedRowParser() and rowParserFinished() to be defined by the user
125+
// It then allows to read the first row in the same way as default parsing way, like:
126+
// while (cp.parseRow()) {
127+
// char *str = ((char**)cp["my_strings"])[0];
128+
// }
129+
122130
if (rowParserFinished())
123131
return false;
124-
rows_count = 0;
132+
133+
// It is necessary to deallocate memory for previously saved strings
134+
// (because strdup is used for saving strings which allocates new memory)
135+
if (rows_count > 0) {
136+
for (int col = 0; col < cols_count; col++) {
137+
if (fmt[col] == 's')
138+
free(((char**)values[col])[0]); // 0 stands for the first row, the use of parseRow implies that only 1 row is parsed at a time
139+
}
140+
rows_count = 0;
141+
}
142+
125143
while (!rowParserFinished() && rows_count == 0)
126144
*this << feedRowParser();
127145
// thanks to the line below the csv could end without '\n' and the last value

library.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name=CSV Parser
2-
version=1.1.0
2+
version=1.1.1
33
author=Michal Borowski <michalmonday17@gmail.com>
44
maintainer=Michal Borowski <michalmonday17@gmail.com>
55
sentence=CSV Parser for Arduino.

0 commit comments

Comments
 (0)