I have the following code:
function get_unlimited_input
allocates a new string if NULL
was passed, otherwise it just appends characters to the existing string.
In the end it truncates excess bytes.
(DEFAULT_BUFFER_SIZE
was set to 5
to test case of many reallocations)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEFAULT_BUFFER_SIZE 5
char *get_unlimited_input(char *buffer) {
size_t current_size;
if (buffer == NULL) {
buffer = malloc(DEFAULT_BUFFER_SIZE * sizeof(char));
current_size = DEFAULT_BUFFER_SIZE;
} else {
current_size = strlen(buffer) + DEFAULT_BUFFER_SIZE;
}
char *cursor = buffer + current_size - DEFAULT_BUFFER_SIZE;
for (;;) {
int current = getchar();
*cursor = (char)current;
cursor++;
if (current == '
' || current == EOF)
break;
if (cursor >= buffer + current_size) {
current_size += DEFAULT_BUFFER_SIZE;
buffer = realloc(buffer, current_size);
cursor = buffer + current_size - DEFAULT_BUFFER_SIZE;
}
}
*cursor = '';
buffer = realloc(buffer, cursor - buffer);
return buffer;
}
int main() {
printf(">");
char *buffer = get_unlimited_input(NULL);
printf(">");
get_unlimited_input(buffer);
}
In most cases it works just fine, but if I pass 117 characters first, and then 12 it crashes:
>.....................................................................................................................
>............
realloc(): invalid next size
Aborted (core dumped)
python3 -c "print('.'*117+'
'+'.'*12)" | ./_buffer
realloc(): invalid next size
Aborted (core dumped)
What is the problem?
question from:
https://stackoverflow.com/questions/65891246/realloc-invalid-next-size-while-trying-to-handle-input-of-unknown-size 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…