首页 文章

scanf在读取文件时给出分段错误

提问于
浏览
0

这个赋值要求我们只使用我们被告知要使用的特定变量 . 这意味着我们无法创建任何自己的 . 这是导致分段错误的代码:

int mem[100];
    int *instructionCounter;
    int *instructionRegister;
    int *operationCode;
    int *operand;
    char str[20];
    memset(str, 0 , 20);
    scanf("%d %s %d" , instructionCounter, str, operand); //this is where the error occurs

我尝试使用fgets而不是scanf来读取字符串 . 我成功读入了字符串,并尝试使用sscanf根据需要解析它 . 但是,由于int指针实际上并不指向任何变量,因此我也收到了分段错误 . 但就像我说的那样,我不允许创建除上面列出的变量之外的任何其他变量 . 这就是我采用这种方法的原因 .

我该怎么做才能避免这种分段错误错误?除了scanf之外还有什么办法可以解决这个问题吗?谢谢你的帮助 .

2 回答

  • 2

    C是一种指针语言,在使用指针之前,请记住,您需要为指针分配一个内存区域,以确保它们在进程的虚拟内存地址空间中引用有效的内存地址 .

    因此,您的代码应该如下所示:

    int mem[100];                     // allocated in stack
    int instructionCounter;           // allocated in stack
    int instructionRegister;          // allocated in stack
    int operationCode;                // allocated in stack
    int operand;                      // allocated in stack
    char str[20];                     // allocated in stack
    
    memset(str, '\0' , sizeof(str));
    if (scanf("%d %s %d" , &instructionCounter, str, &operand) == 3)
        …use the values…
    else
        …report erroneous input…
    
  • 1

    这是我在编译启用警告的代码时得到的结果:

    $ make CC=clang
    clang -fsanitize=address -g -Wall -Wextra -Wno-unused-variable -Wno-unused-parameter   -c -o testme.o testme.c
    testme.c:15:24: warning: variable 'instructionCounter' is uninitialized when used here [-Wuninitialized]
        scanf("%d %s %d" , instructionCounter, str, operand); //this is where the
                           ^~~~~~~~~~~~~~~~~~
    testme.c:9:28: note: initialize the variable 'instructionCounter' to silence this warning
        int *instructionCounter;
                               ^
                                = NULL
    testme.c:15:49: warning: variable 'operand' is uninitialized when used here [-Wuninitialized]
        scanf("%d %s %d" , instructionCounter, str, operand); //this is where the
                                                    ^~~~~~~
    testme.c:12:17: note: initialize the variable 'operand' to silence this warning
        int *operand;
                    ^
                     = NULL
    2 warnings generated.
    clang -fsanitize=address testme.o   -o testme
    

    请注意,编译器不希望您使用这些未初始化的变量,但其解决方案可以解决该问题,但不能解决问题 . 您还必须分配这些变量 .

    试试这个:

    int instructionCounter;
    int operand;
    char str[20];
    memset(str, 0 , 20);
    scanf("%d %s %d" , &instructionCounter, str, &operand);
    

相关问题