2013-09-10 65 views
0

我正在製作一個詞法分析器,這是一個函數。該函數將char,c作爲參數,並將此char附加到已定義的char *數組(yytext)的末尾。然後它增加文本的長度(yylen)。附加char *數組的段錯誤

當它進入此功能時,我不斷收到顯示行上的段錯誤。我在這裏做錯了什麼?謝謝。

BTW:不能使用strncpy()函數/ strcat的,等(但如果你願意,你可以告訴我太那個執行)

這是我的代碼:

extern char *yytext; 
extern int *yylen; 

void consume(char c){ 
    int s = *yylen + 1;     //gets yylen (length of yytext) and adds 1 
             //now seg faults here 
    char* newArray = new char[s]; 
    for (int i = 0;i < s - 1;i++){ 
     newArray[i] = yytext[i];    //copy all chars from existing yytext into newArray 
    } 
    newArray[s-1] = c;      //append c to the end of newArray 
    for (int i = 0;i < s;i++){    //copy all chars + c back to yytext 
     yytext[i] = newArray[i]; 
    } 
    yylen++; 
} 
+0

更新代碼:現在segfaults在不同的線路上。 –

+0

'yylen'是否指向有效值的有效內存位置? – Mahesh

回答

0

能科技工作:

int s = (int)yylen + 1;     //gets yylen (length of yytext) and adds 1 
char newArray[s]; 

使用malloc或大到足夠多的緩衝

char * newarray=(char*)(malloc(s)); 
+0

如何使用char * newArray = new char [s]; –

+0

是的,我也認爲這是C因爲你標籤 – dzada

+0

對不起。我只是改變了這一點。 –

1

你有

extern int *yylen; 

但嘗試使用它,像這樣:

int s = (int)yylen + 1; 

如果變量是int *,使用它像一個int *和反引用得到int。如果它應該是int,則聲明它。

+0

所以我可以將它改爲 extern int yylen; 或 int s =(int)* yylen + 1; –

+0

是的,這取決於該程序的其他部分如何使用該變量。 (你不需要在後面的情況下,順便說一句) –

+0

呃,你不需要* cast * –

0

每個C風格的字符串都應該以null結尾。從您的描述看來,您需要在c附加字符。所以,你需要2個額外的位置(一個用於追加字符,另一個用於空終止符)。

接下來,yylen的類型爲int *。您需要取消引用它以獲取長度(假設它指向有效的內存位置)。所以,嘗試 -

int s = *yylen + 2; 

我沒有看到臨時數組的需要,但可能有一個原因,你爲什麼要這樣做。現在,

yytext[i] = newArray[i];    //seg faults here 

你必須檢查是否yytext指向一個有效內存位置。如果是,那麼足夠長以填充附加字符加空終止符。

但我會建議使用std::string比使用字符數組。使用它可以解決問題。