What does this mean and how do I rectify it *** stack smashing detected ***: ./array1output terminated

Question

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);
}

Show source
| c   | arrays   | gcc   | loops   2017-01-02 04:01 2 Answers

Answers ( 2 )

  1. 2017-01-02 04:01

    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++).

  2. 2017-01-02 07:01

    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);
    }
    
◀ Go back