简体   繁体   中英

Segmentation fault upon reading in a string to a char *

I'm trying to write what I thought would be a simple program, but I'm running into some issues. When I try to read in a string to a char pointer, I get a segmentation fault, but only in certain parts of the code. I feel like it's an issue with the way I'm reading in the string, but I don't get any more information than segfault.

Here is my code:

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


int main() {
    char *Q_or_U;
    char *E_or_P;
    int entry;
    int rc;

    while(1) {

        printf("Would you like to query or update? (q/u): ");
        rc = scanf("%s", Q_or_U);
        if (rc != 1) break;
        printf("received %s\n", Q_or_U);

        if (strcmp(Q_or_U, "q") == 0 || strcmp(Q_or_U, "Q") == 0) {
            //execution fine in this block
            printf("Which entry would you like to query? ");
            rc = scanf("%d", &entry);
            if (rc != 1) break;
            printf("received %d\n", entry);
        }


        else if (strcmp(Q_or_U,"u") == 0 || strcmp(Q_or_U, "U") == 0) {
            //misbehaving
            printf("Would you like to encrypt that message? (y/n): ");
            rc = scanf("%s", E_or_P); //segmentation fault
            if (rc != 1) break;
            printf("received %s", E_or_P);

        }
    }
}

The segfault always occurs upon trying to read a string into my variable E_or_P, what am I missing? (I am new to C).

Both your variables are pointers, but they point to random bytes in the universe. It is just luck which one results in a crash when you write to that place.

You need to make them point to some valid memory to be allowed to write there.

One way is to use malloc ( char *Q_or_U = malloc(30); ), another is to declare them with memory ( char Q_or_U[30]; or so).

The char pointers you declare are just uninitialized pointers. They point at random memory addresses and you are trying to write to those addresses.

Either you have to declare them as static arrays or dynamically allocate memory.

char Q_or_U[SIZE];

or

char *Q_or_U;
Q_or_U=(char*)malloc(SIZE*sizeof(char));

But it seems you only want to read one character, so it should be enough without both arrays and pointers:

char Q_or_U;
rc = scanf("%c", &Q_or_U);

Note the "&". For more information about that, read about c pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM