如何避免以下程序的分段错误?

时间:2017-11-10 18:40:11

标签: c

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

这是我计算给定文本行中每个字符频率的逻辑 但该程序似乎没有显示预期的输出

我得到的是:分段错误(Core dumped) 请给我一些建议!

3 个答案:

答案 0 :(得分:1)

您在scanf中传递的指针值未初始化。访问该垃圾值会调用未定义的行为。

分配一些内存,然后将其传递给scanf

您只需使用char s[10]即可。或者你可以动态分配它。

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

..

free(s);

答案 1 :(得分:0)

&#39; S&#39;是字符指针,它没有指向任何有效的内存。采用s [100]之类的静态数组或动态分配内存。

char *s;

替换上述语句
char *s =  malloc(n*sizeof(char)); // scan 'n' value from user.

一旦完成工作,使用free()函数释放动态分配的内存。

free(s);

答案 2 :(得分: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
相关问题