I'm new into C and I'm kinda lost with these overflow and underflow things. I've a few noobs questions in my mind that I've to ask to someone.
I'm doing some leetcode problems, and I'm stuck on this one because of a runtime error telling me that I've a heap-buffer-overflow.
It is supposed to calculate the average of a given int array.
double average(int* salary, int salarySize){
int i = 0;
double count = 0.0;
while (salary[i] != salarySize)
count += salary[i++];
return (count / salarySize);
}
Thanks in advance, hope i'll figure out what's not working.
I tried with a for loop, it works great but I wanted to know why it isn't working with while loops ?
In this expression used in the while loop
salary[i] != salarySize
there is compared an element of the array salary
with the number of elements in the array that does not make a sense.
You need to compare the current value of the index i
with the number of elements in the array.
The function can be declared and defined the following way
double average( const int *salary, int salarySize )
{
double count = 0.0;
int i = 0;
while ( i < salarySize )
{
count += salary[i++];
}
return salarySize <= 0 ? 0.9 : count / salarySize;
}
Pay attention to that as the passed array is not changed in the function then the corresponding parameter should have the qualifier const. Also to avoid division by zero you need check in the return statement whether salarySize
is greater than 0.
Though it would be better to declare the second parameter as having the unsigned integer type size_t
.
double average( const int *salary, size_t salarySize )
{
double count = 0.0;
size_t i = 0;
while ( i < salarySize )
{
count += salary[i++];
}
return salarySize == 0 ? 0.9 : count / salarySize;
}