Ð
МакÑим Фомин
I need function similar to ReadLine() in any other language.
The program below fails[1] when data more then LAG_SIZE is passed
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
char * read_line(void)
{
bool read_more = true;
enum { LAG_SIZE = 32 };
char *return_buf = NULL;
char *new_line_pos = NULL;
char tmp_buf[LAG_SIZE] = {'\0'};
size_t size = 0;
while (read_more && fgets(tmp_buf, LAG_SIZE, stdin)){
char *tmp_realloc;
size += LAG_SIZE;
tmp_realloc = realloc(return_buf, size);
if (!tmp_realloc){
free(return_buf);
return_buf = NULL;
break;
}
return_buf = tmp_realloc;
memset(return_buf + size - LAG_SIZE, '\0', LAG_SIZE);
new_line_pos = strchr(tmp_buf, '\n');
if (new_line_pos){
*new_line_pos = '\0';
read_more = false;
}
strcat(return_buf, tmp_buf);
memset(tmp_buf, '\0', LAG_SIZE);
}
return return_buf;
}
void loop(void)
{
bool repeat = true;
while (repeat){
char *command;
printf("Enter> ");
command = read_line();
if (command && !strcmp(command, "exit"))
repeat = false;
free(command);
}
}
int main(void)
{
loop();
return 0;
}
[1]: *** glibc detected *** ./a.out: realloc(): invalid next size:
0x0804b008 ***
The program below fails[1] when data more then LAG_SIZE is passed
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
char * read_line(void)
{
bool read_more = true;
enum { LAG_SIZE = 32 };
char *return_buf = NULL;
char *new_line_pos = NULL;
char tmp_buf[LAG_SIZE] = {'\0'};
size_t size = 0;
while (read_more && fgets(tmp_buf, LAG_SIZE, stdin)){
char *tmp_realloc;
size += LAG_SIZE;
tmp_realloc = realloc(return_buf, size);
if (!tmp_realloc){
free(return_buf);
return_buf = NULL;
break;
}
return_buf = tmp_realloc;
memset(return_buf + size - LAG_SIZE, '\0', LAG_SIZE);
new_line_pos = strchr(tmp_buf, '\n');
if (new_line_pos){
*new_line_pos = '\0';
read_more = false;
}
strcat(return_buf, tmp_buf);
memset(tmp_buf, '\0', LAG_SIZE);
}
return return_buf;
}
void loop(void)
{
bool repeat = true;
while (repeat){
char *command;
printf("Enter> ");
command = read_line();
if (command && !strcmp(command, "exit"))
repeat = false;
free(command);
}
}
int main(void)
{
loop();
return 0;
}
[1]: *** glibc detected *** ./a.out: realloc(): invalid next size:
0x0804b008 ***