簡體   English   中英

讀取文件時scanf給出分段錯誤

[英]scanf giving segmentation fault when reading in file

此分配要求我們僅使用被告知要使用的特定變量。 這意味着我們無法創建自己的任何東西。 這是導致分段錯誤的代碼:

    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之外,我還有其他方法可以解決此問題嗎? 謝謝你的幫助。

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…

這是在啟用警告的情況下編譯代碼時得到的結果:

$ 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM