Home > Net >  why does this C input function crash?
why does this C input function crash?

Time:10-11

#include <stdio.h>

int input(char *s, int n){

    char c;
    int i = 0;

    while((c = getchar()) != '\n' && i < n){
          s[i  ] = c; // assigns s[i] then does i  
    }

    s[i]= '\0';

    return i;
}

int main() {

    char array[10];

    input(array, 10);

    printf("%s", array);

}

I have written this code but it does not work.

When i input something it crashes and my shell aborts. Why is this?

CodePudding user response:

s[i]= '\0';

This will access the array out of bound when you enter more than 9 characters.

To prevent this read max n-1 chars.

while((c = getchar()) != '\n' && i < n-1){
  • Related