I've created my own readline function, which reads a variable-size line from the standard input. It's been some time I've not practice much C or C++. Here's my implementation
char* readline(){
size_t n = 10;
char* final = malloc(n * sizeof(char));
final[0] = '\0';
char* tmp; // used for allocating memory temporarily
// constant buffer size used to store the read characters
// before storing them in the final buffer
char buf[10];
while(fgets(buf, 10, stdin) != NULL) {
if(buf[strlen(buf) - 1] == '\n') {
if(strlen(buf) > 1) {
if((n - strlen(final)) < (strlen(buf) + 1)) {
n = strlen(final) + strlen(buf); // -1 because buf contains also \n at the end
tmp = malloc(n * sizeof(char));
for(int i=0; i <= strlen(final); ++i)
tmp[i] = final[i];
free(final);
} else {
tmp = final;
}
int i, j;
for(i = strlen(final), j = 0; j <= (strlen(buf) - 2); ++i, ++j)
tmp[i] = buf[j];
tmp[i] = '\0';
final = tmp;
}
break;
} else { // we need to reallocate memory
if((n - strlen(final)) < (strlen(buf) + 1)) {
n *= 2;
tmp = calloc(n, sizeof(char));
// if this happened at least once, copy all the contents of final to tmp
// copy also the '\0' at the end
for(int i = 0; i <= strlen(final); ++i)
tmp[i] = final[i];
free(final);
} else {
tmp = final;
}
// Starts inserting from the '\0' char
// Insert also the '\0' at the end
// printf("strlen(tmp) = %lu\n", strlen(tmp));
for(int i = strlen(tmp), j = 0; j <= 9; ++i, ++j)
tmp[i] = buf[j];
final = tmp;
}
}
return final;
}
**Questions**
1. Is it correct? Is memory allocation well-performed? Of course the user must then deallocate the memory.