Taking input string from keyboard in C using pointer notation? [duplicate]

青春壹個敷衍的年華 提交于 2021-01-29 20:45:07

问题


I am trying to take in string from keyboard. When I tried this it didn't work.

char *s;
fgets(s,80, stdin);

I get a segmentation fault when I am trying to use the above code. However when I use below code it works, and I don't get a segmentation fault.

char s[81];
fgets(s, 80, stdin);

Why do I segmentation fault when I try to store the string using pointer (char *s)?


回答1:


This is because when you do

char *s;

at this point of time s has garbage value, pointing to an invalid address. Dereferencing it will lead to undefined behaviour, in your case you get segmentation fault.

You need to allocate some memory first using malloc.

s = malloc (sizeof (char) * 81);
fgets (s, 80, stdin);

And, after you are done with the memory, always remember to free it using

free (s);

This will help you obvious memory leakage in larger programs.




回答2:


Because you haven't allocated any memory to store the string in the first example. In the first example, you have a local uninitialized pointer (which means it has some garbage value). When you call fgets, your program attempts to overwrite the memory wherever this pointer is pointing to. Because you haven't allocated this space, you get a segmentation fault.

Your 2nd example, char s[81];, does not throw a segfault because you have allocated 81 bytes on the stack which is what fgets will use to overwrite.



来源:https://stackoverflow.com/questions/28423752/taking-input-string-from-keyboard-in-c-using-pointer-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!