2015-04-03 67 views
0

此分配要求我們只使用我們被告知使用的特定變量。這意味着我們不能創造我們自己的任何一個。這是導致段錯誤的代碼:scanf在文件中讀取時給出分段錯誤

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還有什麼辦法可以解決這個問題嗎?謝謝你的幫助。

+3

你的整數指針不指向任何地方,所以運行時的崩潰抱怨。這個是正常的。實際上,你需要整數變量(而不是指向整數的指針),然後傳遞'&instructionCounter'。字符串不需要&符號,所以'str'是可以的。 memset()並不是真的有必要,儘管它也沒有害處。您應該使用'%19s'而不是'%s'來防止事故發生(緩衝區溢出事故)。 – 2015-04-03 02:04:13

+0

你有沒有試過把這些指針指向實際的'int',比如'mem'數組中的那些? – SleuthEye 2015-04-03 02:06:10

回答

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