2016-10-26 35 views
-1

所以我試圖從getline函數中獲取字數,但是我一直在收到分段錯誤錯誤。在這裏,你可以假定空白只會被定義爲'\ t','\ n'和''。如何從getline做一個字數?

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

int tokenCount(char *mystring){ 
    int word=0; 
    char *ptr = mystring; 
    int i; 

    for(i=0; i<strlen(mystring);i++){ 

      if(ptr[i]!=' ' || ptr[i]!= '\t' || ptr[i]!='\n'){ 
        word++; 

        while(ptr[i]!= ' ' || ptr[i]!= '\t' || ptr[i] != '\n'){ 

         i++; 
        } 
      } 

    } 


return word; 
} 

int main(){ 

    size_t n = 10; 
    char *mystring = malloc(10); 

    if(mystring==NULL){ 
      fprintf(stderr, "No memory\n"); 
      exit(1); 
    } 

    while(getline(&mystring, &n, stdin)>0){ 


      printf("%d\n", tokenCount(mystring)); 
    } 

return 0; 
} 

回答

0
while(ptr[i]!= ' ' || ptr[i]!= '\t' || ptr[i] != '\n'){ 

所以,在英語,而在i空格字符,i製表符,i的值是而不是換行符。看到問題了嗎?如果ptr[i]'a',那麼它通過了這個測試,因爲它不是空格(好)。但如果它是' '(空格字符),它仍然通過,因爲它等於' ',它不等於'\t',所以循環繼續(壞)。這是一個無限循環,並且由於它增量爲i,所以您將指針引用到未分配內存和崩潰的數組末尾。

修復測試中使用的&&,不||,並確保你沒有達到字符串的結尾執行之前(也,緩存strlen之初,不重新計算一遍又一遍):

size_t mystringlen = strlen(mystring); 

... 

if (ptr[i]!= ' ' && ptr[i]!= '\t' && ptr[i] != '\n') { 
    ++word; 
    while(i < mystringlen && ptr[i]!= ' ' && ptr[i]!= '\t' && ptr[i] != '\n'){ 

... 

有輕微的邏輯變化(捕獲更多的空白字符),這可能是與isspace被簡化:

if (!isspace(ptr[i])) { 
    ++word; 
    while(i < mystringlen && !isspace(ptr[i])){ 
+0

不說一聲,正確的做法是聯合國定義的行爲

相關問題