ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
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.
I'm learning C at the moment and am confused about how to dynamically allocate memory at runtime.
If I wanted to read a variable sized string from stdin, how could I do that? I assume I can use scanf but what do I use as the variable for scanf. How can I allocate the memory for the scanf variable before I know how long the string is, but how can find out the size of the string before I've read it in.
Does that make sense? Am I getting things totally wrong?
You are asking two separate questions. How to limit the amount of data input, to avoid buffer overflows and other BAD THINGS. And, how to allocate memory for said buffers at runtime. The answer is that you can allocate memory with the malloc/calloc/alloca family of functions (and then free() the memory when done). The amount of memory allocated can then be used as an argument in a call to 'fread()'. The data thus acquired can be parsed using sscanf(), or strtok(), or any number of other ways, depending upon your requirements.
buf= 1234567, strlen (buf)= 7, s= 1234567...
<= YOU'LL NOTICE THAT "FGETS" AUTOMATICALLY TRUNCATES THE
STRING TO THE LENGTH YOU SPECIFIED (INCLUDING ONE BYTE FOR
THE '\0' STRING TERMINATOR)
A bit on paulsm4's solution above. Notice that he uses a call to fgets. This function makes sure the buffer isn't overflown, unlinke it's sister/cousin/whatever function gets(). Always make sure you use the former and not the latter.
Also note that in the above example, paulsm4 uses buf and s; which have the same value and thus seem (are?) unneeded. He did this to show you what the return value of fgets() is. You should check out `man fgets` (check out the portion of gets() too; also make sure to read the "return value" section).
I suppose what you want to do is allocate exactly as much memory as you need in order to store the string. There is no real way of doing this, as you have no control on the user's input. Here's something you could do: