Harsh Bhudolia
Harsh Bhudolia

Reputation: 153

Character Array and Null character

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    char str[4];

    scanf("%s",str);
    printf("%s",str);
}

input scan output scan

Here I declare an array of 4 characters. I used '%s' that is used for strings. I am not able to understand how can we input 4 char elements and get correct answer when one space should be utilized for the NULL character. The input should only work with up to 3 elements.

Upvotes: 2

Views: 131

Answers (2)

hanie
hanie

Reputation: 1885

as mentioned when you take more than 3 character as input ,and extra chars and \0 will be written outside of array memory(after it) and over write memory which doesn't belong to array.which will cause undefined behavior.

but you can use these to prevent buffer overflow from happening:

scanf("%3s",str);

or

fgets(str, sizeof str, stdin)

Upvotes: 2

Hellmar Becker
Hellmar Becker

Reputation: 2982

scanf() does not check its arguments. You could even enter more than 4 characters and scanf() would happily overwrite the memory area that comes after your array. After that, your program might crash or all kinds of funny things might happen. This is called a buffer overflow and it is a common cause of vulnerabilities in software.

Upvotes: 4

Related Questions