Re: Proper way to input a dynamically-allocated string
- From: websnarf@xxxxxxxxx
- Date: 9 Dec 2005 19:20:43 -0800
Michel Rouzic wrote:
> I know it must sound like a newbie question, but I never really had to
> bother with that before,
Its not. Even experienced programmers seem not to know the proper
answer to this question (hint:fgets() is hardly adequate.)
> [....] and I didn't even find an answer in the c.l.c FAQ
Not much of a surprise there.
> I'd like to know what's the really proper way for input a string in an
> array of char that's dynamically allocated. I mean, I wish not to see
> any such things as char mystring[100]; I don't want to see any number
> (if possible) I just want to declare something like char *mystring; and
> then I don't know how allocate it with just as many chars (with the
> space for the \0 of course) as you get from stdin.
You have to understand, this is a foreign concept to many if not most
of the readers of this newsgroup. Every string container must have a
size, and "the C way" is to declare that size up front. You can search
the archives of this newsgroup to endless examples of this. The C
library is almost completely useless on this issue as well.
> I'd really like to know once for all what's the smartest way of
> inputing strings from stdin and storing them in a way so they take just
> the needed space and I don't want to see any number such as 100 or
> 10,000 or even 4,294,967,296 in my code. Any way it can be done?
You can read my solution to this problem here:
http://www.pobox.com/~qed/userInput.html
The key point is that the C standard library does not provide
provisions for reading a line of dynamically sized string. 1) gets()
is a deterministic overflow and 2) fgets() is inadequate. So no matter
what, for a really correct and useful solution you have to roll your
own algorithm (but it is doable as the link above demonstrates.)
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- Follow-Ups:
- Re: Proper way to input a dynamically-allocated string
- From: Mark McIntyre
- Re: Proper way to input a dynamically-allocated string
- From: Richard Heathfield
- Re: Proper way to input a dynamically-allocated string
- References:
- Proper way to input a dynamically-allocated string
- From: Michel Rouzic
- Proper way to input a dynamically-allocated string
- Prev by Date: Re: C, really portable?
- Next by Date: Re: Invalid read of size 1
- Previous by thread: Re: Proper way to input a dynamically-allocated string
- Next by thread: Re: Proper way to input a dynamically-allocated string
- Index(es):
Relevant Pages
|