2017-10-16 46 views
0

當我運行下面的節目,我有這個問題。一切都編譯得很好,但是當我運行它並輸入內容時,我收到了分段錯誤消息。它不是一個完整的代碼,只是它的一部分,它應該將一些字符串(地址)從輸入文件寫入字符串數組,然後在數組中搜索可能的搜索字符串(作爲參數輸入)。我該怎麼做「分段故障(核心轉儲)」的錯誤?(沒有找到答案其他地方)

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

int main(int argc, char *argv[]) 
{ 
    char *entry1 = argv[1], *adress[100], *possibleAdress[100], c; 
    int i,j,k,possible = 0; 

    while(c = getchar()!=EOF)   //write addresses to array 
    { 
    while(c = getchar()!=13) 
     { 
     adress[i][j] = c; 
     j++; 
     } 
     i++; 
    } 

    i = 0; 

    while(adress[i]!=0)  //find adresses matching with search enrty 
    { 
    j = 0; 
    while(adress[i][j]!=0) 
    { 
     while(entry1[j]==adress[i][j]) 
     j++; 
     if(j==strlen(entry1))  //check if the whole search entry is matching 
     { 
     possibleAdress[k] = adress[i]; 
     k++; 
     } 
     i++; 
    } 
    } 
    return 0; 
} 
+0

我j和k都沒有被初始化中使用的,程序調用未定義的行爲。 – George

+1

此外,您還沒有爲'adress'和'possibleAdress'分配任何內存,所以您正在將值寫入隨機地址。段錯誤正是正確的迴應。 –

+0

只是改變你的數組,使他們不指針。否則,你將不得不做的@LeeDanielCrocker建議和實際分配的內存爲您陣列明確使用malloc 焦炭取值範=的argv [1],ADRESS [100],possibleAdress [100],C; – victor

回答

2

有一件事我可以清楚地看到不正確的是,你在while循環使用之前,你有沒有初始化主i的值和j。

0

我該怎麼做「分段故障(核心轉儲)」的錯誤?

前一個問題什麼是內存設計缺陷:What is a segmentation fault?

你跟他們做的是打破了一個調試器,GDB例如。然後,您可以逐行逐行執行代碼,通過指令進行指導並瞭解問題的原因。

其他的答案是正確的,我& j是初始化。調試將允許您檢查這些變量和內存訪問。

0

你需要大量的修正。要增加一個指針,你需要分配足夠的內存給它。你的while循環完全錯誤,你試圖增加指針值而不分配內存,這就是它給你sig故障錯誤的原因。

第一變化這一行:int i=0,j=0,k=0,possible = 0;

現在while循環

while(c = getchar()!=EOF)   //write addresses to array 
{ 
    j = 0; 
    char *p = malloc(30);// size should be change as per your requirement 
    address[i] = p; //store the address of p here 
    while(c = getchar()!=13) 
    { 
    *((adress[i])+j) = c; //it is just like *p++ = c 
    j++; 
    } 
    i++; 
}