-2

What is problem with my code, that it shows "stack smashing detected" Problem Statement: Given an array, we have to find the smallest element in the array.

#include<stdio.h>
int main(){
    int arr[20],i,j,c,x,num;
    scanf("%d",&num);
    for(x=0;x<num;x++){
        scanf("%d",&arr[x]);
    }
    for(i=0;i<sizeof(arr)-1;i++){
        if(arr[i]>arr[i+1]){
            c=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=c;
        }
    }
    printf("%d",*(arr+0));
    return 0;
}

2 Answers2

0

If the user-provided value num is greater than 20, your code will write to memory off the end of the array arr. This is undefined behaviour, and likely to cause a crash.

GKFX
  • 1,386
  • 1
  • 11
  • 30
0

Two problems:

(1) int arr[20] can only hold twenty values, but you let the user put in any number.

(2) sizeof(arr) gives you the size in bytes, not the number of elements.

The compiler is able to detect one or both of these problems, and give you an error message telling you.

CoffeeTableEspresso
  • 2,614
  • 1
  • 12
  • 30