Question: So I'm writing a small program (I'm new to C, coming from C++), and I want to take in a string of maximum length ten.

I declare a character array as

```
#define SYMBOL_MAX_LEN 10 //Maximum length a symbol can be from the user (NOT including null character)
.
.
.
char symbol[SYMBOL_MAX_LEN + 1]; //Holds the symbol given by the user (+1 for null character)

```

So why is it when I use:

```
scanf("%s", symbol); //Take in a symbol given by the user as a string

```

I am able to type '01234567890', and the program will still store the entire value?

My questions are:

1. Does scanf not prevent values from being recorded in the adjacent
blocks of memory after `symbol`?
2. How could I prevent the user from entering a value of greater than length `SYMBOL_MAX_LEN`?
3. Does scanf put the null terminating character into `symbol` automatically, or is that something I will need to do manually?

Answer: 
You can limit the number of characters `scanf()` will read as so:

```
#include <stdio.h>

int main(void) {
    char buffer[4];
    scanf("%3s", buffer);
    printf("%s\n", buffer);
    return 0;
}

```

Sample output:

```
paul@local:~/src/c/scratch$ ./scanftest
abc
abc
paul@local:~/src/c/scratch$ ./scanftest
abcdefghijlkmnop
abc
paul@local:~/src/c/scratch$

```

`scanf()` will add the terminating `'\0'` for you.

If you don't want to hardcode the length in your format string, you can just construct it dynamically, e.g.:

```
#include <stdio.h>

#define SYMBOL_MAX_LEN 4

int main(void) {
    char buffer[SYMBOL_MAX_LEN];
    char fstring[100];
    sprintf(fstring, "%%%ds", SYMBOL_MAX_LEN - 1);
    scanf(fstring, buffer);
    printf("%s\n", buffer);
    return 0;
}

```

For the avoidance of doubt, `scanf()` is generally a terrible function for dealing with input. `fgets()` is much better for this type of thing.
> 
> I am able to type '01234567890', and the program will still store the entire value? 
> 
> 
> 

This is because you are Unlucky that you are getting your desired result. This will invoke undefined behavior. 

> 
> Does `scanf` not prevent values from being recorded in the adjacent blocks of memory after symbol? 
> 
> 
> 

No. 

> 
> How could I prevent the user from entering a value of greater than length SYMBOL\_MAX\_LEN? 
> 
> 
> 

Use `fgets`. 

> 
> Does scanf put the null terminating character into symbol automatically, or is that something I will need to do manually? 
> 
> 
> 

Yes