🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.g++.lib.bug
Article #576

Run-time error when using 'get' with an istream object

#576
From: Doug Lea
Date: Thu, 08 Feb 1990 10:48
59 lines
2154 bytes
> I am having trouble using the 'get' method for the 'istream' class.
> It generates a 'Segmentation fault' error at run-time.  I know the
> 'istream' is being opened correctly because reading into a 'String'
> object with >> works fine.  Am I doing something wrong ?
> The sample program and "data" illustrate the point:
> 
> main()
> {
>     istream from("data",io_readonly,a_useonly);
>     char *line;
> 
>     from.get(line,15);
>     cout << line;
> }
> 
> Sample "data" file contents:
> word1 word2
> word3
> 

There are 3 istream functions for reading char*'s 

  istream&      get    (char* s, int n, char terminator = '\n');
  istream&      getline(char* s, int n, char terminator = '\n');
  istream&      gets   (char **s, char terminator = '\n');
 
The first two *require* an allocated char* (they differ only
in how the trailing terminator is handled.) To use them, you
must supply either a char[N] or an allocated char*.
The third automatically allocates space for you, that you should
later delete.

For example,

main()
{
    istream from("data",io_readonly,a_useonly);
    char *line = new char[16]; // enough for string + null
    char line2[16];
    char* line3 = 0; // `= 0' so delete'able even if never allocated --
                     // Not necessary in this example.

    from.get(line,15);
    from.get(line2,15);
    from.gets(&line3,15);  // pass in the addr of line3

    cout << line;
    cout << line2;
    cout << line3;

    delete line;
    delete line3;
}

Using the String class is a very good way to avoid dealing with these
kinds of char* allocation and semantics issues.

-Doug
Technical Details
Message-ID: <9002081048.AA03595@g.oswego.edu>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!watserv1!watmath!uunet!tut.cis.ohio-state.edu!G.OSWEGO.EDU!dl
References: <9002072328.AA07167@CSServer.CS.MsState.Edu>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!watserv1!watmath!uunet!tut.cis.ohio-state.edu!G.OSWEGO.EDU!dl
From: dl@G.OSWEGO.EDU (Doug Lea)
Newsgroups: gnu.g++.lib.bug
Subject: Run-time error when using 'get' with an istream object
Message-ID: <9002081048.AA03595@g.oswego.edu>
Date: 8 Feb 90 10:48:50 GMT
References: <9002072328.AA07167@CSServer.CS.MsState.Edu>
Sender: daemon@tut.cis.ohio-state.edu
Reply-To: dl@oswego.oswego.edu
Distribution: gnu
Organization: GNUs Not Usenet
Lines: 59