我正在製作一個詞法分析器,這是一個函數。該函數將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++;
}
更新代碼:現在segfaults在不同的線路上。 –
'yylen'是否指向有效值的有效內存位置? – Mahesh