i need function reproduce basic of getline function program, function should able read fp , without huge buffer (256 should enough here) have 2 problem on code below - function start return wrong info when buffer exeeded, file example http://pastebin.com/bxj3sh92 ( ./a.out < file ) - when call function without giving file should work cat stop after press first enter key ( ./a.out )
here code:
#define moar_buf 256 #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <stdio.h> char *my_getline(const int fd) { static char save[moar_buf]; static int = moar_buf; int g; int f; char *save2; save2 = null; g = 0; f = 0; if (g == 0 && >= (moar_buf -1)) { = 0; g = read(fd, save, moar_buf + 1); save[g] = '\0'; } if (i <= moar_buf && save[i] != '\0') { save2 = malloc((sizeof(*save2) * moar_buf)); while(save[i] != '\n' && save[i] != '\0') save2[f++] = save[i++]; save2[f] = '\0'; if (save[i] != '\0') = + 1; } return(save2); } int main() { int i; char **converted_map; char *map; = 0; converted_map = malloc(sizeof(*converted_map) * 30); while(map = my_getline(0)) { converted_map[i] = strdup(map); printf("%s\n", converted_map[i]); i++; } }
static char save[moar_buf]; g = read(fd, save, moar_buf); save[g] = '\0'; you tell read read moar_buf bytes, , when succeeds reading many, 0-termination writes past end of array, invoking undefined behaviour.
you need tell read read fewer bytes, moar_buf - 1 example, or make buffer larger, moar_buf + 1, example.
then, in main,
while(map = my_getline(0)) { printf("%s\n", converted_map[i]); converted_map[i] = strdup(map); i++; } you print out converted_map[i] before assigned, that's more undefined behaviour. need first strdup(map) converted_map[i], then can print it.
Comments
Post a Comment