[Techtalk] getline bug or doing it all wrong g++

John Clarke johnc+linuxchix at kirriwa.net
Tue Mar 2 19:47:36 EST 2004


On Mon, Mar 01, 2004 at 11:53:47PM -0800, Tintin J Marapao wrote:

> I was wondering if anyone knows of a getline bug in gcc 3.31 ...  or 
> perhaps I am not using the getline correctly?

Neither of the above, well, other than 

> char line[];
> char test[0]= "hello world";
> 
> ...
> 
> 
> ifstream in;
> cout << test[0] << endl; //correct result - prints hello world
> in.getline( line, delimiters);
> cout << test[0] << endl; // prints the value of line!!

That's because you've declared test as an array of length zero, and
line as an array of unknown size.  I don't know how you even got the
code to compile:

    [johnc at dropbear ~/tmp]$ cat test.C
    char line[];
    char test[0]= "hello world";

    [johnc at dropbear ~/tmp]$ g++ -c test.C
    test.C:1: storage size of `line' isn't known
    test.C:2: initializer-string for array of chars is too long
    test.C:1: storage size of `line' isn't known

    [johnc at dropbear ~/tmp]$ g++ -v
    Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs
    gcc version 2.96 20000731 (Red Hat Linux 7.3 2.96-113)

If you somehow manage to convince the compiler to compile your code,
you'll have two arrays which are too short to hold the data which
you're trying to store, and writing to one will overwrite the other.

Try this instead:

    [johnc at dropbear ~/tmp]$ cat test.C
    #include <iostream>
    #include <fstream>

    char line[1000];        // I hate fixed length buffers but it's OK
                            // to use one to demonstrate the problem
    char test[]= "hello world"; // no dimension needed here - the
                                // initialiser tells the compiler how
                                // much space to allocate

    int main(void)
    {
        ifstream in;
        cout << test << endl;           // note, no [0] after test
        in.getline(line, sizeof(line)); // tell getline() how big the
                                        // buffer is
        cout << test << endl;           // note, no [0] after test
        return 0;
    }

    [johnc at dropbear ~/tmp]$ g++ -o test test.C
    [johnc at dropbear ~/tmp]$ ./test
    hello world
    hello world


Cheers,

John
-- 
NETBUEI is a fine protocol for a private non-routed network of less than
ten machines that don't need to talk to any other networks.  In other
words, it's of almost no value in practice.        -  Mike Sphar


More information about the Techtalk mailing list