Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does this C input function crash?

#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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading