2017-03-01 57 views
-2

我試圖用fgets接受來自用戶的「地址」的多條線路,但我有一個Segmentation fault (core dumped)就像我離開while循環。我可以在沒有任何問題的循環中printf兩個addresspart_of_address變量,而在循環它按預期工作。一旦擺脫循環,它就會着火。接受多行()

// Define a char array called 'name' accepting up to 25 characters. 
char name[25]; 
// Define a char array called 'part_of_address' accepting up to 80 characters. 
char part_of_address[80]; 
// Define a char array called 'address' accepting up to 80 characters. 
char address[80]; 

// Clean the buffer, just to be safe... 
int c; 
while ((c = getchar()) != '\n' && c != EOF) {}; 

// Ask for the user to enter a name for the record using fgets and stdin, store 
// the result on the 'name' char array. 
printf("\nEnter the name of the user (RETURN when done):"); 
fgets(name, 25, stdin); 

// Ask for the user to enter multiple lines for the address of the record, capture 
// each line using fgets to 'part_of_address' 
printf("\nEnter the address of the user (DOUBLE-RETURN when done):"); 
while (1) 
{ 
    fgets(part_of_address, 80, stdin); 
    // If the user hit RETURN on a new line, stop capturing. 
    if (strlen(part_of_address) == 1) 
    { 
     // User hit RETURN 
     break; 
    } 
    // Concatinate the line 'part_of_address' to the multi line 'address' 
    strcat(address, part_of_address); 
} 

printf("This doesn't print..."); 
+0

初始化數組您最有可能通過反覆串聯文本溢出了'address'。 – StoryTeller

+1

如果用戶從不輸入地址,則會發生分段錯誤。 – kneeki

+0

你可以只用'strcpy()'第一個字符串,然後'strcat()'休息。 – RoadRunner

回答

1

正如評論指出的邁克爾·瓦爾茲,您使用strcat(address, part_of_address);甚至在第一次,而不必初始化address。由於它是一個自動數組,它包含未定義的值,並且您正在調用未定義的行爲。很可能,即使是第strcataddress陣列後覆蓋內存。

只是char address[80] = "";char address[80] = {'\0'};