Re: [Vala] Initializing strings to be used by FileStream::gets



Hi Daniel,

On Sun, 2007-09-09 at 11:57 +0100, Daniel Thompson wrote:
I am playing with vala and am starting out by playing with the string
handling (always an interesting area when C and other languages meet).

I used the following code to attempt to simulate 'cat' with no
arguments.

var str = new string();
while (!stdin.eof()) {
      stdin.gets(str, 256);
      stdout.printf("%s", str);
}

Of course such code is broken because the string has only sufficient
space allocated for the '\0' terminator meaning that fgets() will
overrun the memory allocated for str (got this from review of the
generated C code and proved it with valgrind).

I've therefore been trying to figure out how best to grow a string to be
large enough to store the input from fgets. The best I have so far
developed without modifying the bindings is:

var str = "%*d".printf(256, 0);

This at least allows 256 to be a numeric constant somewhere and runs
cleanly with valgrind but it really is pretty grubby.

Have I missed something obvious? If not does anyone have any advice on
how I should improve the bindings?

The string class in Vala should be treated as immutable in most cases,
just like the String classes in C# and Java. I'd recommend you to use
GLib.String (GString in C) if you want a string class that is better
suitable for modification. GLib.String can be compared to the
StringBuilder classes in C# and Java, maybe we should rename the class
in the Vala bindings to reduce some confusion about "string" and
"String".

Something like the following should work:

var str = new String.sized (256);
stdin.gets (str.str, 256);

What do other people think about renaming GLib.String to
GLib.StringBuilder?

Jürg




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]