0

Trying to understand malloc and calloc, so I watched some of TheNewBoston's video about the subject. But for some reason I get a really strange output, let me show the code to start with.

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

int
main()
{
  int i, howMany;
  int total;
  float average = 0.0;
  int * pointsArray;

  printf("How many do you want to store: \n");
  scanf("%d", &howMany);

  pointsArray = (int *) malloc(howMany * sizeof(int));

  printf("Enter your numbers: \n");

  for(i = 0; i < howMany; i++)
    {
      scanf("%d", &pointsArray[i]);
      total += pointsArray[i];
    }
  average = (float)total / (float)howMany;

  printf("Average is: %f\n", average);

  free(pointsArray);

  return 0;
}

It is supposed to calculate the mean value of the numbers you enter. The problem is that the value of the variable "total" get a start value of 4195808 for some reason. First I made an own "interpretation" of TheNewBoston's code, but after I got this error I just copied it but the same problem remains. Why does this happen? I can not find any info about anyone having a similar problem.

Salviati
  • 758
  • 2
  • 9
  • 28
  • [do-i-cast-the-result-of-malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – LPs Dec 01 '16 at 13:55
  • 3
    Try `int total=0;` instead of `int total;` – r3mainer Dec 01 '16 at 13:55
  • 2
    It makes sense that your total variable should start at zero. You have to state that in your program: `int total = 0;` , otherwise who knows what `total` will start at , 4195808 is as good a starting point as any. – nos Dec 01 '16 at 13:57
  • Unbelievable, sometimes I just stare myself blind. It worked, thank you! But the question remains, how come that just 4195808 was assigned all the time? It must have been a "junk" memory byte that sneaked in but I have rebooted the computer one time and it was still 4195808 after the reboot. Just interested. – Salviati Dec 01 '16 at 14:00
  • Stepping through your code with a debugger, or adding debug print statements would help you figure this out on your own. – Jonathon Reinhart Dec 01 '16 at 14:00
  • 4
    Also, your compiler should be warning you that you're using the variable uninitialized. Turn up or pay attention to the warnings. – Jonathon Reinhart Dec 01 '16 at 14:01
  • Ty for that clarification! – Salviati Dec 01 '16 at 14:02
  • I used -Wall -Werror and -pedantic but no warnings – Salviati Dec 01 '16 at 14:03
  • With GCC, you need some level of optimization to get warnings about uninitialized variables. Add `-O` or `-O3` to your options. Don't compile without it unless you're about to use the debugger. (Consider adding `-Wextra` to your list too.) – Jonathan Leffler Dec 01 '16 at 14:29

5 Answers5

6

You didn't initialize total, so the value is undefined. Some compilers/runtimes might, by sheer coincidence, happen to have zero on the stack, others might have arbitrary values left behind by C runtime initialization there. If you want total to be initially zero, initialize it to zero:

int total = 0;
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

get a start value of 4195808 for some reason.

The reason is that int total; has automatic storage duration (stack allocated), so its init value is indeterminate.

That is Undefined Behavior.

From the ISO/IEC 9899:201x @ page 158

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

You have to explicitly init local variables, so

int total = 0;
LPs
  • 16,045
  • 8
  • 30
  • 61
2

A variable declared inside of a function without being initialized has an indeterminate value. Attempting to access it without initializing results in undefined behavior.

Compiling this code with a different compiler or with different optimization settings for example could cause this indeterminate value to change.

From section 6.7.9 of the C standard:

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
...

You should explicitly initialize this variable to a known value.

int total = 0;

As for why the same "random" value was being used each time, the variable in question was declared in main, so whatever its initial value is is probably based on how the the program starts up. The OS should wipe any memory assigned to a new process for security reasons, so rebooting shouldn't affect it.

If the variable in question was in a function other than main, then it's initial value will be dependent on where in the program flow the function was called and what functions were called before it that left data on the stack.

Again however, this is undefined behavior. Other compilers don't have to be consistent with this behavior, so don't depend on it.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

You don’t initialize the total value, which means it contains a “random” value before you start adding your numbers to it. Just initialize the total to zero and it will work. Here’s an older answer to a similar question that goes into more depth about local variable initialization in C.

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354
1

It was the previous value stored in the memory cell reserved to total variable. Initialize it to 0

Igino Boffa
  • 411
  • 2
  • 6
  • 26