0

Each time I run this c code I get a segmentation fault (core dumped)...so the array gets printed and everything and in the end of the printing it fives me this segmentation fault...I tried putting a break after the if, the error code does not appear but it only now reads one line and doesn't read multiple

int main(int argc, char* arg[]){
    if (argc != 2){ 
        puts("Error: Usage is caesarcipher <offset>");
        exit(1);
    }
    int i = 0;
    int input;
    char array[100];
    while ((input = getchar())!= '\0'){
        if (input == '\n'){
            array[i] = '\0'; 
            printf("%s\n", array);
            i = 0;
        }else{  
            array[i] = input;
            i += 1;}}
        return 0;
    }
}
1
  • 1
    So you have nothing to prevent you from writing past the end of the array[100] array. Certainly, if you input more than 100 characters a segmentation fault is not only possible but likely. For starters, add checks to see if I is >99 and abort. However, if the lines you are reading are short, I don't know why you are getting the fault. Commented Feb 19, 2020 at 1:18

1 Answer 1

2

You should check the documentation for getchar(), particularly the return value which indicates an error.

Sign up to request clarification or add additional context in comments.

2 Comments

en.cppreference.com/w/c/io/getchar. "Return value: The obtained character on success or EOF on failure." EOF is never the same as '\0'.
yes I understood...the code worked...thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.