2013-04-09 75 views
0

我正在C中運行一個程序。當我運行該程序時,出現分段錯誤錯誤。 IN gdb當我回溯它時告訴我當strlen產生分段錯誤時,來自GetString()的C字符串

程序接收到的信號SIGSEGV,分段錯誤。 __strlen_sse2_bsf()在../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.S:51 51 MOVDQU(%EDI), %XMM1

我相信這與strlen的做。

我使用strlen唯一的一次是:

string s = GetString(); 

    int stringlength = strlen(s); 

當我改變的strlen用於sizeof停止錯誤。

我的代碼有什麼問題?的GetString

/* 
* Reads a line of text from standard input and returns it as a 
* string (char *), sans trailing newline character. (Ergo, if 
* user inputs only "\n", returns "" not NULL.) Returns NULL 
* upon error or no input whatsoever (i.e., just EOF). Leading 
* and trailing whitespace is not ignored. Stores string on heap 
* (via malloc); memory must be freed by caller to avoid leak. 
*/ 

string GetString(void) { 
    // growable buffer for chars 
    string buffer = NULL; 

    // capacity of buffer 
    unsigned int capacity = 0; 

    // number of chars actually in buffer 
    unsigned int n = 0; 

    // character read or EOF 
    int c; 

    // iteratively get chars from standard input 
    while ((c = fgetc(stdin)) != '\n' && c != EOF) 
    { 
     // grow buffer if necessary 
     if (n + 1 > capacity) 
     { 
      // determine new capacity: start at 32 then double 
      if (capacity == 0) 
       capacity = 32; 
      else if (capacity <= (UINT_MAX/2)) 
       capacity *= 2; 
      else 
      { 
       free(buffer); 
       return NULL; 
      } 

      // extend buffer's capacity 
      string temp = realloc(buffer, capacity * sizeof(char)); 
      if (temp == NULL) 
      { 
       free(buffer); 
       return NULL; 
      } 
      buffer = temp; 
     } 

     // append current character to buffer 
     buffer[n++] = c; 
    } 

    // return NULL if user provided no input 
    if (n == 0 && c == EOF) 
     return NULL; 

    // minimize buffer 
    string minimal = malloc((n + 1) * sizeof(char)); 
    strncpy(minimal, buffer, n); 
    free(buffer); 

    // terminate string 
    minimal[n] = '\0'; 

    // return string 
    return minimal; 
} 
+1

GetString是做什麼的?我猜你沒有終止你的字符串... – 2013-04-09 01:55:24

+0

什麼是''字符串'? ''std :: string''或''char *''? – gongzhitaao 2013-04-09 01:56:23

+0

@LeeTaylor我假設它返回一個C字符串。那麼你的問題是string是一個C++類型,而strlen需要一個以null結尾的字符數組。 – SevenBits 2013-04-09 01:56:58

回答

4

getString()功能的描述的

文檔明確指出,它可以在一個錯誤或EOF返回NULL。

如果傳遞的返回值strlen()不檢查,你的程序會崩潰。

string s = GetString(); 
int stringlength = 0; 

if (s != 0) 
    stringlength = strlen(s); 

這至少不會崩潰。

您可能還注意到多少混亂的原因typedef char *string;和效益如何賦予一點,並把它帶到心臟。你不必重複那些教你的人的錯誤。

我也觀察到的代碼片段:

// minimize buffer 
string minimal = malloc((n + 1) * sizeof(char)); 
strncpy(minimal, buffer, n); 
free(buffer); 

可以更好,更簡單,寫成:

string minimal = realloc(buffer, n + 1); 

縮小分配給正確的尺寸。

+0

謝謝,在我使用strlen之前檢查字符串爲null解決了我的問題。謝謝 – IberoMedia 2013-04-09 05:39:19

相關問題