I noticed that when reading a string using scanf in C, it is possible for a string to exceed the amount of characters allocated to it. When this happens I usually encounter a segmentation fault or abort. I've made a quick demo below.
char string[50];
scanf("%s", string);
string[49] = '\0';
Now, if a user were to enter something longer than 50 chars, the code would crash. I tried solving this by adding string[49] = '\0'
however that does not seem to be fixing the problem. I understand there is an alternative with fgets
, however I do not want the user to be able to write spaces.