Skip to content

Commit 0bd5e62

Browse files
committed
Fixing potential crash in readline function caused by neglecting result of realloc
1 parent b9ba442 commit 0bd5e62

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/fileio/scan.c

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,15 @@ static ssize_t readline(char** lineptr, size_t* n, FILE* stream) {
6060
}
6161
p = bufptr;
6262
while (c != EOF) {
63-
if ((ssize_t)(p - bufptr) > (ssize_t)(size - 1)) {
64-
size = size + 128;
65-
bufptr = realloc(bufptr, size);
66-
if (bufptr == NULL) {
63+
if ((ssize_t)(p - bufptr)+1 > (ssize_t)(size)) {
64+
size_t offset = p - bufptr; // save offset
65+
size = size + 128;
66+
char * new_buf = realloc(bufptr, size);
67+
if (new_buf == NULL) {
6768
return -1;
6869
}
70+
bufptr = new_buf;
71+
p = bufptr + offset; // recalculate p using the saved offset
6972
}
7073
*p++ = c;
7174
if (c == '\n') {

0 commit comments

Comments
 (0)