【问题标题】:How to avoid segmentation fault for the below program? [duplicate]如何避免以下程序的分段错误? [复制]
【发布时间】:2017-11-10 18:40:10
【问题描述】:
#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);
    }
}

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

我得到的是:分段错误(核心转储) 请给我一些建议!

【问题讨论】:

  • char *s; 没有内存分配:它是一个未初始化的指针。建议以char s[1024]; 为例,并限制scanf 中的输入长度。
  • char s[100];scanf("%99[^\n]", s);,注意格式说明符中不需要s
  • 旁白:避免硬编码数字魔术:for(i = 'a'; i &lt;= 'z'; i++)(假设连续编码,但通常是这种情况)。
  • 不得在您的格式中的%[^\n] 后面有s

标签: c


【解决方案1】:

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

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

您可以简单地使用char s[10]。或者您可以动态分配它。

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

..

free(s);

【讨论】:

    【解决方案2】:

    's' 是字符指针,它没有指向任何有效的内存。要么采用像 s[100] 这样的静态数组,要么动态分配内存。

    char *s;
    

    将上面的语句替换为

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

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

    free(s);
    

    【讨论】:

      【解决方案3】:

      您尚未为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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 2019-01-02
        • 2019-05-30
        相关资源
        最近更新 更多