2017-11-10 2 views
0
#include<stdio.h> 

int fcount(char ch, char *a){ 
    if(*a == '\n'){ 
     printf("d"); 
     return 0; 
    } 
    else 
     if(*a == ch){ 
      printf("b"); 
      return 1 + fcount(ch, a++); 
     } 
     else 
      if(*a!=ch){ 
       return fcount(ch, a++); 
     } 
} 

int main(){ 
    char *s; 
    int c = 0, i; 
    printf("Enter anything you wish\n"); 
    scanf(" %[^\n]s",s); 
    for(i = 97; i <= 122; i++){ 
     c = fcount(i, s); 
     if(c != 0) 
      printf("[%c] %d\n", i, c); 
    } 
} 

これは、テキスト の与えられたラインで各文字の頻度をカウントするために私のロジックである。しかし予想出力以下のプログラムでセグメンテーションフォールトを回避するにはどうすればよいですか?

を表示するように見えるdoesntのプログラムは、私が取得すると、このです:セグメンテーションフォールト(コアダンプ) アドバイスをお願いします!

+1

'char * s;'はメモリ割り当てがありません。初期化されていないポインタです。 'chars [1024];を提案し、' scanf'で入力長を制限してください。 –

+2

'char s [100];'と 'scanf("%99 [^ \ n] "、s);'は書式指定子に 's'は必要ないことに注意してください。 –

+1

脇に:(i = 'a'; i <= 'z'; i ++) '(連続したエンコーディングを仮定していますが、通常は*です)。 –

答えて

1

scanfで渡したポインタ値が初期化されていません。そのゴミ値にアクセスすると、未定義の動作が呼び出されます。

メモリを割り当ててからscanfに渡してください。

char s[10]をそのまま使用できます。または、動的に割り当てることができます。

s = malloc(sizeof(char)*10); 
if(s == NULL){ 
    fprintf(stderr,"%s"<"Error in malloc"); 
    exit(1); 
} 

.. 

free(s); 
0

's'は文字ポインタであり、有効なメモリを指していません。 s [100]のような静的配列を取るか、動的にメモリを割り当てます。

char *s; 

無料()関数を使用して動的に割り当てられたメモリを解放し、

char *s = malloc(n*sizeof(char)); // scan 'n' value from user. 

と作業が行われた後に上記のステートメントを置き換えます。

free(s); 
0

sにメモリを割り当てていません。それにはmallocを使います。

char *s; 
s=(char*)malloc(21*sizeof *s); // Suppose you want at the most 20 chars in s 
if(NULL == s){ 
    printf("Memory allocation failed\n"); 
    exit(1); // Exiting with a non-zero exit status 
} 

//Also, instead of scanf use fgets 
fgets(s,21,stdin); // Does some bounds checking. 
s[strlen(s)-1]='\0'; // Getting rid of newline character at the end, so mallocing 21 makes sense 
関連する問題