ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
But, can you explain:
1) (very interesting to me)
I've scanf(%s, somebuf); in my program, and how do I know, the size to allocate for incoming text?
In general, can I use scanf function and avoid SYGFAULT? If I can't - nor static, nor dynamic, what should I do to handle and allocate in memory incoming string with unknown size.
2) This code is sometime works:
char *string;
scanf("%s", string);
Smometimes works, sometimes SYGFAULTs, why?
I do not allocate any memory to it, how can it work?
As far as I know, you can't use scanf with the %s escape on untrusted input; there is no way to keep it from overflowing. You can use something like %50s, which says that you want to get at most 50 characters. I think that is 50+1 including the \0, but I didn't verify.
If that code snippet works, it is by chance. string had some uninitialized value in it, and it happened to be a memory address which was writable by you. This means you scribbled on a random part of your program's memory, and it might crash later on. Alternatively, the pointer could point to somewhere non-writable, in which case you will get a seg fault on the scanf(). This is one of the beautiful parts of debugging unititialized pointers: They may work fine until you change a completely unrelated bit of code, and then the program can start crashing.
hehe nope wouldnt have a clue what argv and c are but i know that i just want to read from the file, not write to it too, thats a seperate part of the program
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.