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);
    }
}

This is my logic to count the frequency of each character in a given line of text But the program doesnt seem to display the expected output

what I get is this: Segmentation fault(Core dumped) Please offer me some advice!

pm100
  • 48,078
  • 23
  • 82
  • 145
Abdulbasith
  • 139
  • 1
  • 8

3 Answers3

1

The pointer value that you passed in scanf is uninitialized. Accessing that garbage value invokes Undefined behavior.

Allocate some memory and then pass it to scanf.

You can simply use char s[10]. Or you can allocate it dynamically.

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

..

free(s);
user2736738
  • 30,591
  • 5
  • 42
  • 56
0

's' is character pointer and its not pointing to any valid memory. Either take static array like s[100] or allocate memory dynamically.

char *s;

replace above statement with

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

and once work is done, free the dynamically allocated memory using free() function.

free(s);
Achal
  • 11,821
  • 2
  • 15
  • 37
0

You haven't allocated memory to s. Use malloc for that.

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
sjsam
  • 21,411
  • 5
  • 55
  • 102