mmollle mmollle - 11 months ago 37
C Question

C program is behaving giving weird values in Windows but works fine in Ubuntu

I wrote a program for a small task in school on my laptop with Ubuntu on. I wasnt having any problems when writing the program. It worked perfectly fine and did everything it should. But when I moved it over to my Windows PC it gave me some very weird values and I cant seem to figure out whats wrong with it. I use the same IDE, CodeBlocks 16.01, on both Ubuntu and Windows. Ive been trying to solve this for several hours but im stuck so I would really appreciate some help.

If I for example enter the value 50 on every prompt I will get the results of 200 in both printf-methods after the while-loop, like it should be since 50+50+50+50 equals 200. In windows however I get 240 in total_weight and 100 in total_height which to me doesnt make any sense. Whats the cause of this?

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

int main()
int weights[3], heights[3], i = 0;
int total_weight, total_height;

while (i <= 3)
printf("Person %d, enter your weight (kg): ",i+1);
printf("Person %d, enter your height (cm): ",i+1);
scanf("%d", &heights[i]);

//Calculations for total weight and total length of all the people
total_weight = total_weight + weights[i];
total_height = total_height + heights[i];

printf("\n\tPerson %d's weight and height: %dkg, %dcm\n\n", i+1, weights[i], heights[i]);

//Printing the results of the earlier calculations
printf("\tTotal weight of everyone: %d\n", total_weight);
printf("\tTotal height of everyone: %d\n", total_height);

return 0;


Answer Source

In your code, by saying

 while (i <= 3)

you're going off-by-one. This invokes undefined behavior, for out-of-bound memory access.

To elaborate, C arrays have 0-based indexing. So for an array with a dimension of 3, will have valid indexes from 0 to 2, inclusive.

So, you should use

while (i < 3)

to stay in the bounds.

That said, in your code, total_weight and total_height are automatic local variables and they are used uninitialized. Hence, they contain indeterminstic values and using them causes UB, again. You have to explicitly initialize them to, say, 0.