GNOME Bugzilla – Bug 642040
wrong c code generated for array parameters
Last modified: 2016-10-11 12:46:14 UTC
valac 0.10.0 and 0.11.5 generates wrong c code for array parameters. private int mysum(int values[]) { int s = 0; foreach (var v in values) s+=v; return s; } public static int main (string[] args) { stdout.printf("%d\n", mysum( { 1, 2, 3 } )); return 0; } compiling with valac gives: In function ‘mysum’: warning: assignment makes pointer from integer without a cast In function ‘_vala_main’: warning: passing argument 1 of ‘mysum’ makes integer from pointer without a cast note: expected ‘gint’ but argument is of type ‘gint *’ The reason seems to be that the c code generated for mysum is wrong: gint mysum (gint values, int values_length1) where I believe the correct code would have been: gint mysum (gint *values, int values_length1)
Please note that this is invalid code.
Do you mean that the vala or the c code is invalid? If you refer to the vala code, in which way is it not valid? And if it is indeed invalid vala code, I would have expected the vala compiler to complain. (Note that in my setup the code actually works, despite the warning; probably because gint has the same size as a pointer)
Sorry, I thought I wrote a longer comment here. There are two different types of arrays in Vala: inline/stack-allocated arrays and pointer-based/heap-allocated arrays. For parameters you can only use the latter. The correct code is: private int mysum(int[] values) { int s = 0; foreach (var v in values) s+=v; return s; } public static int main (string[] args) { stdout.printf("%d\n", mysum( { 1, 2, 3 } )); return 0; } And yes, valac should definitely complain. That's what needs to be fixed.
Thanks for the explanation! (1) I can confirm that your code compiles without warning and works. (2) Here is another example, where valac is happy, but the c compiler barfs: int[] a = new int[3]; a = { 1, 2, 3 }; int b[] = a; (3) Why would the mysum function care whether the array is stack or heap allocated? As far as I can see even a stack allocated array would be in scope for the duration of the callee... (4) I think it would be great to have a better explanation of the difference between "type[] var" and "type var[]" at http://live.gnome.org/Vala/Tutorial#Arrays and http://live.gnome.org/Vala/Manual/Types#Reference_types The tutorial only says "If you put the square brackets after the identifier together with an indication of size you will get a fixed-size array. Fixed-size arrays are allocated on the stack [...]" which I interpret as "type var[size]", but does not mention "type var[]"
*** This bug has been marked as a duplicate of bug 641308 ***