-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; } 
6
  • 2
    Welcome to Stack Overflow. Please read How to Ask and ericlippert.com/2014/03/05/how-to-debug-small-programs, and try to trace through the logic of the code. Hint: what do you expect to be the result of sizeof(arr)? What is the result? Do you understand why? Commented Jun 8, 2022 at 17:42
  • 1
    What if num > 20? Commented Jun 8, 2022 at 17:42
  • 2
    Always check user input. Always. Commented Jun 8, 2022 at 17:47
  • I'm asking for less than 20. But still same result. Commented Jun 8, 2022 at 17:50
  • Questions seeking debugging help should generally provide a minimal reproducible example of the problem, which includes the exact input required to reproduce the problem. Commented Jun 8, 2022 at 18:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I'm aware of first one, but the second point cleared my doubt. Thankyou...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.