473,782 Members | 2,437 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper way to input a dynamically-allocated string

I know it must sound like a newbie question, but I never really had to
bother with that before, and I didn't even find an answer in the c.l.c
FAQ

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.

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?

Dec 9 '05
48 2254

Flash Gordon wrote:
Michel Rouzic wrote:
Eric Sosman wrote:
Other observations: `int' should probably be `size_t'


as for the size_t thing, well i could cast it for realloc, like this :
mystring=reallo c(mystring, (size_t) i+1);


Why on earth would you think that? You *really* need to start working
through a decent text book.
> other than that, I think i
should leave it to int, unless it is ok to do iterations and refer to
some element of an array by a size_t, which i doubt


Again, what on earth makes you think that? Of course you can use a
size_t variable for indexing in to an array.


ok cool, so why shouldn't I use an int for the size in a realloc, or
why again shouldn't I cast it to size_t?

Dec 10 '05 #21
Michel Rouzic wrote:

Flash Gordon wrote:
Michel Rouzic wrote:
Eric Sosman wrote:
> Other observations: `int' should probably be `size_t'

as for the size_t thing,
well i could cast it for realloc, like this :
mystring=reallo c(mystring, (size_t) i+1);


Why on earth would you think that?
You *really* need to start working
through a decent text book.
other than that, I think i
should leave it to int,
unless it is ok to do iterations and refer to
some element of an array by a size_t, which i doubt


Again, what on earth makes you think that? Of course you can use a
size_t variable for indexing in to an array.


ok cool, so why shouldn't I use an int for the size in a realloc, or
why again shouldn't I cast it to size_t?


The integer parameter type of realloc is size_t,
so casting an int argument to type size_t, does nothing.

void *realloc(void *ptr, size_t size);

Do you have some resources available to learn about size_t?

--
pete
Dec 10 '05 #22
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/

Dec 10 '05 #23
"Michel Rouzic" <Mi********@yah oo.fr> writes:
Flash Gordon wrote:
Michel Rouzic wrote:
> Eric Sosman wrote:
>> Other observations: `int' should probably be `size_t'
>
> as for the size_t thing, well i could cast it for realloc, like this :
> mystring=reallo c(mystring, (size_t) i+1);


Why on earth would you think that? You *really* need to start working
through a decent text book.
> other than that, I think i
> should leave it to int, unless it is ok to do iterations and refer to
> some element of an array by a size_t, which i doubt


Again, what on earth makes you think that? Of course you can use a
size_t variable for indexing in to an array.


ok cool, so why shouldn't I use an int for the size in a realloc, or
why again shouldn't I cast it to size_t?


Why *should* you use an int?

The second argument of realloc() is of type size_t. You can use an
int if like (it will be implicitly converted if you have a proper
"#include <stdlib.h>"), but there's no good reason to do so.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 10 '05 #24
sl*******@yahoo .com wrote:
Michel Rouzic wrote:
I know it must sound like a newbie question, but I never really
had to bother with that before, and I didn't even find an answer
in the c.l.c FAQ

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.

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?


From stdin is a bit of a problem. The usual answer is to use a
buffer to temporarily store the string:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


.... snip code ...

Or you can get my ggets routine at:
<http://cbfalconer.home .att.net/download/ggets.zip>

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Dec 10 '05 #25
we******@gmail. com said:
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.)


In my experience, you're wrong; how to do this is common knowledge amongst
experienced programmers.
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.


Most people who ask questions here are newbies, which is why they're asking
questions; that's why we tend to give them simple answers. Nevertheless,
the "how do I get an entire line of input" thing has been asked and
satisfactorily answered many times here.
The C
library is almost completely useless on this issue as well.


That's like saying the toolkit you get with a new bicycle is useless. Well,
yes, it's not brilliant - but it's probably enough to get you up and
rolling on Christmas Day. Serious users will want better in due course, and
quite a few solutions to this problem have been presented in this newsgroup
in the past.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Dec 10 '05 #26
On 9 Dec 2005 19:20:43 -0800, in comp.lang.c , we******@gmail. com
wrote:
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


Don't be silly.
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];


You have to understand, this is a foreign concept to many if not most
of the readers of this newsgroup.


Absolute rubbish. Of course, I do realise you're trolling. But you
really are a chump.
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 10 '05 #27
Michel Rouzic wrote:
Flash Gordon wrote:

Again, what on earth makes you think that? Of course you can use a
size_t variable for indexing in to an array.
ok cool, so why shouldn't I use an int for the size in a realloc,


Apart from the obvious fact that realloc is defined to accept size_t
instead of int, you should consider size_t to be self documenting. That
is, it is immediately obvious what the variable means:

int len;

Oh it's a number of how long something is.

size_t len;

Oh it is how long/large something is in memory.

or why again shouldn't I cast it to size_t?


Because, for very large arrays (I myself haven't seen arrays larger
than 2GB, but it is possible) on 64bit (or 128bit? someday...)
platforms, size_t may or may not be the same size as int. You don't
know, I don't know. But your compiler knows. Using size_t causes your
compiler to treat it properly. On 32bit platforms size_t may end up
being the same as an unsigned int anyway so don't worry about it
generating different code. Leave it to your compiler to decide.

Dec 10 '05 #28
Michel Rouzic wrote:
Flash Gordon wrote:
Michel Rouzic wrote:
Keith Thompson wrote:


<snip>
> The speed of that code while reading input probably isn't going to be
> much of an issue, but the multiple calls to realloc() might cause
> excessive heap fragmentation, which could cause problems elsewhere in
> your program. (The standard does use the term "heap", but you get the
> idea.)

does it mean that the elements of my array won't be contigous?


No, it means the free space in your heap will be fragmented. Any memory
block returned by *alloc is always contiguous.


oh, thats what I thought. But, what are the consequences, I mean, I'll
have some memory occupied, some free space, and then my string, so, as
for the free space, does it mean it could only be used for something
smll enough to fit it, or otherwise it will just be wasted space?


The consequences is that sooner or later malloc/realloc will fail
because it can't find a contigous area of memory as large as the one
you requested. Coupled with your refusal to handle realloc failures,
this will result in a program crash.

Dec 10 '05 #29
Michel Rouzic wrote:
Flash Gordon wrote:
Michel Rouzic wrote:
<snip>
It might not cause a segmentation violation. It might overwrite critical
data instead.
um... i dont think you know what i'm refering to.


I do and you are WRONG.
The example I took is
the one of my program that reads .wav files to deal with them, without
checking that it actually is a .wav file. basically, it will just look
at a precise place in a file for a 32-bit integer telling how many
bytes are to be read in the file. If you try to input a non .wav file
instead, the 32-bit integer read will be bogus, and is likely to have a
value much higher than the number of bytes left in the file, so the
program will try to read even after the it has read the whole file,
thus causing a segmentation fault.
There is absolutely NO guarantee that is will cause a segmentation
fault. For a start that is a term that is not defined in the C standard,
secondly it is a term not applicable to all systems, thirdly almost any
action that could cause a segmentation fault could *also* overwrite some
critical data used by your application, such the FILE structures,
possibly causeing corruption of files on disk.
so basically, as I said, if the user wants to input an mp3 file instead
of a .wav, it's at his own risk. And if you want to input an EOF
character at some point, well, it's at your own risk too, maybe one day
i'll bother with making some stuff to check that kind of foolishness,
but so far i've got more prioritary things to do than this kinda of
stuff (like making sure my program does what it's supposed to do)


One of the *first* things to worry about is making sure that your input
data is correct. As well as the reasons I've also mentioned, i.e. risk
of doing nasty things to your system, which are REAL risks, although the
most likely problem is corrupting either output OR input file (yes, the
input file CAN be corrupted). There is also the risk that the format
gets extended and a wav file contains things you don't handle properly,
causing your program to corrupt things despite being given a real wav file.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Dec 10 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2404
by: Peter Kirk | last post by:
Hi there I have a form which submits a list of data to a web-application (which then saves to a database). The list consists of four input fields per row. Eg. <field_1.1><field_2.1><field_3.1><field_4.1> <field_1.2><field_2.2><field_3.2><field_4.2> <field_1.3><field_2.3><field_3.3><field_4.3> ....
6
3334
by: Thomas | last post by:
Hi, I'm having a problem with the dynamically created inputfields in Internet Explorer. The situation is the following: - I have a dynamically created table with a textbox in each Cell. - It is possible to Add and Delete rows - Some cells have special attributes (readonly and events) Here's a snippet of the code:
5
2101
by: cjl | last post by:
Hey all: This code: if (stealth) { document.searchme.query.type = 'password'; } else {
2
8379
by: crjunk | last post by:
I'm trying to find a way to create input boxes dynamically on the client side but everything that I've come across works with IE, but not FireFox. On my web page, I have the following input boxes: txtAddress1, txtCity1,txtState1, txtZip1 What I'd like to do is to have a button that says "Add Another Location". When the user clicks on the button, then txtAddress2, txtCity2, txtState2, and txtZip2 are created below the first location
1
7496
by: vega80 | last post by:
Hi. I have a problem with assigning an onkeypress-function to dynamically created input-boxes.I want to put the content of an input-field into a tag-list when the user hits enter. This works fine the first time (when the input-field is created in a non-dynamical way). The next input-field is created dynamically by a function that is called when the user hits enter (the previously generated input-field will be hidden). Then I'm trying...
1
1810
by: Steve2007 | last post by:
Hi I have the following form in my html page: <form name="mapserv" method=GET action=""> <input type="hidden" name="timeFiltering"> <input type="hidden" name="filteringType"> <input type="hidden" name="filteringBox"> <input type="hidden" name="Geofence" value="1|Geofence1|-88.19311|30.52311|-87.91011|30.65221|10|3"> <input type="hidden" name="Geofence1" value="1|Geofence1|-88.19311|30.52311|-87.91011|30.65221|10|2">
2
2541
by: Ed Jay | last post by:
I'm dynamically creating several form input elements: mValue = integer constant; for(var j = 0; j < mValue; j++) { target = "imgCn"+ j; eName = "myFile"; eName = eName+jj; document.getElementById(target).innerHTML = "<input type = 'file' name="+eName+" value=''>text"; }
1
1323
by: =?Utf-8?B?QXJuZSBHYXJ2YW5kZXI=?= | last post by:
I am programming input forms in Asp.net 2.0 Some textboxes are static on the form and viewstate works fine. Some textboxes have to be dynamically added to the form at run-time which makes viewstate difficult to maintain. Sometimes I have got viewstate to magically work. Sometime I have to manually restore viewstate. What is the best way to deal with dynamically created input boxes? -- Arne Garvander Certified Geek
4
2976
by: mohaaron | last post by:
I can think of a lot of reasons why this might need to be done but as far as I can tell it's not possible. I've been looking for a way to add HtmlTableRows to a table using a button click for a while and it seems it's not possible because the row that gets added with each click won't get recreated after a post back. After all the reading it seems that any dynamically created controls must be created in the Init event to be recreated after...
0
864
by: davidson1 | last post by:
Hai to Everybody, I am designing a website in ASP.NET , in my project students can view their information such as name,department etc... and many information for students will be displayed... all that information will be taken from database and displayed in ASP.NET so all the tables in asp.net are dynamically created , so i need give good color to dynamically created table in a proper way...... So that it good web design........ if u...
0
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.