2014-11-03 98 views
-1

我試圖從stdin讀取fgets()中的行,我想在函數中使用fgets(),我認爲這是問題所在。該字符串可能最長爲1024個字符。當我運行這段代碼,我得到「分割故障(核心轉儲)」C - 從函數中讀取stdin與fgets()中的函數

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

#define MAX_SIZE 1025 

void print_fgets(); 

int main() 
{ 
    print_select(); 
    return 0; 
} 

void print_select() 
{ 
    char *str; 
    int length; 

    while (fgets(str, MAX_SIZE, stdin)!=NULL) 
    { 
     length=strlen(str); 

     if (length==MAX_SIZE-1 && str[length-1]!='\n') 
     { 
      printf("Error, line overeached buffer!\n"); 
      return 1; 
     } 

     if (str[length-1]=='\n') 
      str[length-1]='\0'; 
     printf("%s\n", str); 
    } 
} 
+0

你在哪裏包括? – HuStmpHrrr 2014-11-03 16:18:32

+5

你沒有爲'str'分配內存。這就是爲什麼。 – HuStmpHrrr 2014-11-03 16:19:18

+0

如何分配內存?我是C中的新成員。 – Krop 2014-11-03 16:20:02

回答

0

的問題是,你嘗試寫入位置的str指針指向。 最初它會指向一些垃圾地址(由於char *str未被初始化)。

你可以嘗試一個基於堆棧的解決方案,而不是通過改變:

/* This is just a pointer */ 
char *str; 

到:

/* This is a character array (on the stack) of size MAX_SIZE, initialized to zero */ 
char str[MAX_SIZE] = {0}; 

或者,如果你想爲陣列的動態分配內存,而是執行此操作:

char *str; 
str = calloc(1, MAX_SIZE); 
if (str == NULL) { 
    /* Failed to allocate memory */ 
} 

... Your code 

free(str); /* You should always free dynamically allocated memory when you are done with it */ 
str = NULL; /* It's a good practice to point your pointer to NULL after it's free'd */ 

不要忘記像0開始的數組索引,然後去MAX_SIZE - 1(在你的情況下)和NUL終止(字符串必須以它結束)。

+1

在這種情況下初始化是不確定的。 'fgets'也*保證* NULL終止。 – sfstewman 2014-11-03 16:24:46

+0

@sfstewman當然,但我認爲初學者總是初始化爲零以避免問題是一種很好的做法。下一分鐘它不是'fgets'這就是所謂的,但其他東西,不保證null終止例如。 – Jite 2014-11-03 16:29:49

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

#define MAX_SIZE 1025 

int print_select(); /* Use correct name (instead of print_fgets()) */ 

int main() 
{ 
    print_select(); 
    return 0; 
} 

int print_select() /* Fix. Dhould return int if you have a return <int> statement. */ 
{ 
    char str[MAX_SIZE]; /* Initialize static memory. */ 
    int length; 

    while (fgets(str, MAX_SIZE, stdin)!=NULL) 
    { 
     length=strlen(str); 
     if (length==MAX_SIZE-1 && str[length-1]!='\n') 
     { 
      printf("Error, line overeached buffer!\n"); 
      return 1; 
     } 
     if (str[length-1]=='\n') 
     { 
      str[length-1]='\0'; 
     } 
     printf("%s\n", str); 
    } 
    return 0; /* Function may not be returning an int. Return it in those cases. */ 
} 
+1

沒有必要再次粘貼整個代碼。使用可用宏'MAX_SIZE'而不是硬編碼'1025'。 – Jite 2014-11-03 16:30:45

+0

是的,對不起。我有點新。 – 2014-11-03 16:34:43