Fix reallocation issues with non-POSIX get_line

This commit is contained in:
ado 2024-02-23 21:56:44 +01:00
parent c0ee100f99
commit c0d3087f85
2 changed files with 4 additions and 4 deletions

View File

@ -62,10 +62,10 @@ ssize_t get_line(char** lineptr, size_t* n, FILE* fp) {
size_t line_used = strlen(*lineptr); size_t line_used = strlen(*lineptr);
size_t buff_used = strlen(buff); size_t buff_used = strlen(buff);
if (*n < buff_used + line_used) { if (*n <= buff_used + line_used) {
size_t new_n = *n * 2; size_t new_n = *n * 2;
auto new_lineptr = static_cast<char*>(realloc(*lineptr, *n)); auto new_lineptr = static_cast<char*>(realloc(*lineptr, new_n));
if (new_lineptr == nullptr) { if (new_lineptr == nullptr) {
errno = ENOMEM; errno = ENOMEM;
return -1; return -1;

View File

@ -674,10 +674,10 @@ ssize_t get_line(char** lineptr, size_t* n, FILE* fp) {
size_t line_used = strlen(*lineptr); size_t line_used = strlen(*lineptr);
size_t buff_used = strlen(buff); size_t buff_used = strlen(buff);
if (*n < buff_used + line_used) { if (*n <= buff_used + line_used) {
size_t new_n = *n * 2; size_t new_n = *n * 2;
auto new_lineptr = static_cast<char*>(realloc(*lineptr, *n)); auto new_lineptr = static_cast<char*>(realloc(*lineptr, new_n));
if (new_lineptr == nullptr) { if (new_lineptr == nullptr) {
errno = ENOMEM; errno = ENOMEM;
return -1; return -1;