Home > OS >  C gives segmentation fault and a warning for two different lines. What can I do to solve this issue?
C gives segmentation fault and a warning for two different lines. What can I do to solve this issue?

Time:01-03

I'm still a beginner in C, but as training I would like to create a Password Manager(a very bad on though). First a .txt file is created, and then the user is given an option of what they would like to do next. Using strcmp I make the program decide what function to execute next. I have two, storeServiceEmailPass(), where the user saves info to the .txt document and readAllData(), where the program prints out all text saved on the document. Using if, else if and strcmp, I make the program choose a function based of the user input.

When I execute the function getUserInput(), it gives me the following warning:

comparison of array 'userInput' equal to a null pointer is always false [-Wtautological-pointer-compare]

and then stops the program, stating: Segmentation fault. It is impossible that this is a null pointer like the error suggests.

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

void createPassDoc() {
    FILE * passfile = fopen("Passwords.txt", "w");
    fclose(passfile);
    printf("File Created.\n");
}

void storeServiceEmailPass() {
    char ServiceEmailPassword[300];
    FILE * passfile = fopen("Passwords.txt", "a");
    printf("Please enter the following: Service, Email, Password.\n");
    fgets(ServiceEmailPassword, 300, stdin);
    fprintf(passfile, "%s", ServiceEmailPassword);
    fclose(passfile); 
}

void readAllData() {
    char savedData[5000];
    FILE * passfile = fopen("Passwords.txt", "a");
    printf("Here is your saved Data:\n");
    while(fgets(savedData, 100, passfile)) {
    printf("%s\n", savedData);
    }
    fclose(passfile);
    }

void getUserInput() {
    char userInput[255];
    char createPass[] = "Store Service\n";
    char readAllPass[] = "Show Passwords\n";

    printf("What would you like to do?\n");
    fgets(userInput, 255, stdin);
    if(strcmp(createPass, userInput == 0)){
        storeServiceEmailPass();
    } else if (strcmp(readAllPass, userInput == 0)){
        readAllData();
    } else {
        printf("Please enter a command such as: Store Service or Show Passwords.\n");
    }
}
int main() {

    createPassDoc();
    getUserInput();

    return 0;
}
```
```

I expected function getUserInput to execute, but it just tells me

segmentation fault

and also gives me the warning:

comparison of array 'userInput' equal to a null pointer is always false [-Wtautological-pointer-compare]

for lines 38 & 40

CodePudding user response:

if(strcmp(createPass, userInput == 0)){

You just have your parentheses misplaced. The comparison should be against the result of the function call, not the second argument.

  • Related