Segmentation fault in c when reading a line -


i want read user input(like terminal) until exit written or ctrl+c/ctrl+d pressed. read every line(until return/enter pressed), check if it's space or comment(#) , execute functions.

i tried 3 methods, no success. error every time insert string , press enter

char line[256]; while(printf("%s>", shell_name) && scanf("%50[^\n]", line) != eof) { 

segmentation fault (core dumped)

while(printf("%s>", shell_name) && getline(line, 100, stdin) != eof) 

note: expected ‘size_t * restrict’ argument of type ‘int’

while(printf("%s>", shell_name) && fgets(line, sizeof(line), stdin) != null) { 

segmentation fault (core dumped)

for more orientation i'm doing next

if(isspace(&line) == 0 && &line[0] != "#") 

what doing wrong? there more suitable/easy/better option?

the segfault kicks in because enter infinite loop: scanf("%50[^\n]", line) reads input , stops @ return. return not consumed , stays in input buffer. happens next time around? scanf checks input buffer, , hey! there return! stops reading. et cetera.

adding space first character inside scanf format string resolves that:

int main() {     char line[256];     char *shell_name = "mysh";      while (printf("%s>", shell_name) && scanf(" %50[^\n]", line) != eof)     {         printf ("you entered [%s]\n", line);     }     printf ("done.\n");     return 0; } 

on further note, wrong:

if(isspace(&line) == 0 && &line[0] != "#") 

-- gcc complains

warning: passing argument 1 of 'isspace' makes integer pointer without cast warning: comparison string literal results in unspecified behavior 

the first on isspace(&line), meant isspace(line[0]), second on &line[0] != "#", can written more concisely line[0] != '#'.


on getline

getline works different other "get stdin" functions, because automatically allocate memory if asked to. since needs return not one, three results (the number of characters, string entered, , length) need provide pointers string , size arguments:

size_t line_size = 0; char *ptr_to_line = null;  while (printf("%s>", shell_name) && getline(&ptr_to_line, &line_size, stdin) != -1)       ... 

when using way, should not use static string size allocation, function fill in appropriate values. (but don't forget uses malloc , realloc internally, make sure free result. uses malloc first time, realloc after resize.)


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -