c - 出现段错误但不知道如何修复它

标签 c arrays pointers debugging segmentation-fault

下面的代码有一个段错误,但我真的不知道如何调试它,也许是因为我缺乏 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]++;
    }

   /* ... */
}

最佳答案

这里

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字符指针数组,它们未初始化,即未指向任何有效地址。解决这个问题的一种方法是为每个char指针分配内存,然后您可以将一些数据放入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])来释放动态内存,以避免内存泄漏

关于c - 出现段错误但不知道如何修复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771834/

相关文章:

C程序可以不用main函数吗?

python - 将 C 函数的指针参数与 python 脚本中的 ctype 参数链接起来

c - 如何计算 CRC32 校验和?

c++ - 如何分离用户输入的字符串并将其存储到数组中

C++:指向不同函数的成员函数指针数组

c - 在 C 中创建字符串并将其传递给函数的最佳方法?

c++ - 如何在类中初始化静态常量指针?

c - gets() 在 C 循环中如何工作?

python - 使用 SWIG 将 C 结构数组访问到 Python

javascript - 检查对象数组中键的每个值是否相等或为 null