3

This is the code. Why am I facing this error and what source of information should I refer so as to rectify such errors so that I get to know 'If I do this that way, I will get 'x' error'

#include<stdio.h>
void main()
{
   int i,avg,sum;
   int marks[30]; // Array declaration

   for(i=0;i<31;i++)
   {
      printf("Enter Marks:");
      scanf("%d",&marks[i]); // Stores data in Array
   }

   for(i=0;i<31;i++)
      sum=sum+marks[i];

   avg=sum/30;
   printf("Average marks of student \t %d",avg);
}
hmofrad
  • 1,784
  • 2
  • 22
  • 28
KshitijV97
  • 347
  • 1
  • 4
  • 16
  • 6
    `for(i=0;i<31;i++)` --> `for(i=0;i<30;i++)` – chux - Reinstate Monica Jan 02 '17 at 03:35
  • 1
    The `int marks[30]` defines an array of size 30 (0..29 indices), but in your `for loops`, you're accessing the marks[30] which does not exist. – hmofrad Jan 02 '17 at 03:38
  • 1
    To add to @MohammadH.Mofrad's answer, when you write to marks[30], you write into memory your program doesnt own. And the program crashes. See this for more info http://stackoverflow.com/questions/1345670/stack-smashing-detected – Sush Jan 02 '17 at 03:40

2 Answers2

2

Whenever you declare a variable in a function it allocates memory on the stack. The stack is a reserved memory area for doing temporary data manipulation within the function. Now in your code you declared 3 ints and one array of ints with 30 slots. In your for loop you are putting 31 ints into 30 slots; from 0 thru 30 are 31 numbers. The last number is being put beyond the 30th slot and therefore "smashing" into the next spot on the stack, in other words overwriting it. The solution would be to change you for loop to for(i=0;i<30;i++).

MotKohn
  • 3,485
  • 1
  • 24
  • 41
0

You have declared an int type array as [30] and have tried to assign 31 values to it. Please note that the array starts from 0. So the for loop should be as mentioned below. for(i=0;i<30;i++) Hence the issue, Please change the for loop and rest are all fine in your code. Thank you. :)

#include<stdio.h>
void main()
{
int i, avg, sum=0;
int marks[30]; // Array declaration

for (i = 0; i<30; i++)
{
    printf("Enter Marks:");
    scanf("%d", &marks[i]); // Stores data in Array
}

for (i = 0; i<30; i++)
    sum = sum + marks[i];
    avg = sum / 30;
printf("Average marks of student \t %d", avg);
}
Vimal Bhaskar
  • 748
  • 1
  • 5
  • 17