Other answers in this thread have mentioned this, but have not provided resources to help you better understand the issue. So, that is what I will do here.
You have created your first buffer overflow error. This is because C does not have memory safety, meaning that there no restrictions on the boundaries of memory unless explicitly implemented by the user.
In your case, the function scanf("%s",name);
gets the data from the user and puts it in the buffer. This function does not check memory boundaries. This means that if the input size is larger than the allocated buffer you are writing outside your allocated memory. In many cases, it is harmless. However, it can be the source of really hard to find bugs and some vulnerabilities. The Wikipedia article about buffer overflow is excellent and explains everything in a lot of detail, which should help you get a better understanding.
The function that you used to read the length of the string strlen(name)
, also does not do a boundary check. If you look at the man page of strlen, you can see that it does not mention anything about memory boundaries. Instead, it states that it calculates the length between the start of the string and the next terminating null byte.
The strlen() function calculates the length of the string pointed
to by s, excluding the terminating null byte ('\0').
So, why does your application work?
You have a function that does not care about memory boundaries when writing, and you have a function that does not care about memory boundaries when reading.
How can you prevent it from happening?
Luckily for you, you are not the first with this problem. If you are interested in understanding how you can prevent this from happening, I recommend you check out this post How to prevent scanf causing a buffer overflow in C? . If you are a beginner, I wouldn't recommend you implement these functions, as some are quite complicated when you are just getting started. However, you can look through the post and see what people are posting and find out more about things mentioned in that post.