【问题标题】:Getting a seg fault but has no idea how to fix it遇到段错误但不知道如何解决
【发布时间】:2019-09-10 07:32:41
【问题描述】:

以下代码有段错误,但我真的不知道如何调试它,可能是因为我缺乏C语法知识,并且我已经阅读了TCPL但仍然无能为力。

#include <stdio.h>
#include <ctype.h>
int main() {
    char *str[4];
    char c[2];
    for (int i = 0; i < 4; i++)
        scanf("%s", str[i]);
    int find = 0;
    while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
        if (isalpha(*str[0]) && *str[0] == *str[1]
            && *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
            find++;
            if (find == 1)
                c[0] = *str[0];
            else if (find == 2)
                c[1] = *str[0];
        }
        str[0]++;
        str[1]++;
    }

   /* ... */
}

【问题讨论】:

    标签: c arrays pointers debugging segmentation-fault


    【解决方案1】:

    这里

    char *str[4]; /* what str[0] contains ? some junk data, need to assign valid address */
    for (int i = 0; i < 4; i++)
       scanf("%s", str[i]); /* No memory for str[i] here */
    

    str字符指针数组 并且它们未初始化,即未指向任何有效地址。解决这个问题的一种方法是为每个字符指针分配内存,然后你可以将一些数据放入str[i]。例如

    char *str[4];
    for (int i = 0; i < 4; i++) {
       str[i] = malloc(MAX); /* define MAX value as per requirement */ 
       scanf("%s", str[i]); /* Now str[i] has valid memory */
    }
    

    一旦使用动态内存完成工作,不要忘记通过为每个字符指针调用free(str[i])来释放动态内存以避免内存泄漏

    【讨论】:

      【解决方案2】:

      您忘记了为字符串分配的内存。

      您的代码具有动态分配的内存。

      #include <stdio.h>
      #include <ctype.h>
      #include <stdlib.h> //needed for malloc and free
      int main() {
          char *str[4];
          //allocate memory
          for (int i = 0; i < 4; ++i) {
              //allocate 128B per string
              str[i] =(char*) malloc(128 * sizeof(char)); 
              //here you should check if malloc was succesfull 
              //if malloc failed you schould free previously allocated memory
          }
          char c[2];
          for (int i = 0; i < 4; i++)
              scanf("%s", str[i]);
          int find = 0;
          while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
              if (isalpha(*str[0]) && *str[0] == *str[1]
                  && *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
                  find++;
                  if (find == 1)
                      c[0] = *str[0];
                  else if (find == 2)
                      c[1] = *str[0];
              }
              str[0]++;
              str[1]++;
          }
          //delete memory
          for (int i =0; i < 4; ++i) {
              free(str[i]);
          }
         /* ... */
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多