简体   繁体   English

将字符串读入char时出现分段错误*

[英]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. 当我尝试将字符串读入char指针时,我遇到了段错误,但仅限于代码的某些部分。 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? 尝试将字符串读取到变量E_or_P中时,总是会发生段错误,我缺少什么? (I am new to C). (我是C新手)。

Both your variables are pointers, but they point to random bytes in the universe. 您的两个变量都是指针,但是它们指向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). 一种方法是使用malloc( char *Q_or_U = malloc(30); ),另一种方法是使用内存声明它们( char Q_or_U[30];左右)。

The char pointers you declare are just uninitialized pointers. 您声明的char指针只是未初始化的指针。 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. 有关此的更多信息,请阅读有关c指针的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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