【问题标题】:Hello! I don't know what's causing segmentation fault in my code. May I know why? and what I should do to fix it?你好!我不知道是什么导致我的代码出现分段错误。我可以知道为什么吗?我应该怎么做才能解决它?
【发布时间】:2022-07-26 22:22:20
【问题描述】:

**我遇到了分段错误,我不知道为什么。我感觉这是由 if(isPalindrome(str_array[i]) == 0) 下的代码引起的,但我不知道是哪一个以及如何处理它。

附:我仍然是一名学生,所以如果该建议与我在这里的代码水平相差无几,我将不胜感激。谢谢你。 **

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int isPalindrome(char check[]);


int main() {
    int array_size = 5, i;
    char *str_array[array_size], *palindrome_array[array_size], str_length[100];

    for(i = 0; i < array_size; i++) {
        printf("Enter word #%d: ", i+1);
        scanf("%[^\n]%*c", str_length); //"%[^\n]%*c : pattern matching - allows inputs to have spaces

        str_array[i] = (char*) malloc(sizeof(char) * strlen(str_length));
        strcpy(str_array[i],str_length); 

        if(strcmp(str_array[i],"exit") == 0) {
            break;
        }
    
        if(isPalindrome(str_array[i]) == 0) {
            palindrome_array[i] = (char*) malloc(sizeof(char) * strlen(str_length));
            strcpy(palindrome_array[i], str_length); 
            printf("'%s' is a palindrome \n", palindrome_array[i]);
        } else printf("'%s' is NOT a palindrome \n", str_array[i]);
    }


    //BONUS: prints all the palindrome strings inputted
    printf("Your palindrome words are: \n");
    for(i = 0; i < array_size; i++) {
        printf("%d.)%s \n", i+1, palindrome_array[i]);
    }

    return 0;
}


int isPalindrome(char check[]) {        // from string to individual characters
    int middle = strlen(check) / 2;     //gets the half of the string's length
    int length = strlen(check);

    for(int i = 0; i < middle; i++) {
        if(check[i] != check[length - i - 1]) {
            return 1;
        } 
    } return 0;
}   

【问题讨论】:

  • str_array 不是必需的。或者更确切地说,它不需要是一个数组。还有一种可能是您没有初始化palindrome_array 的所有指针。为palindrome_array 保留一个单独的计数器,而不是使用array_size。或者确保初始化数组的所有指针。

标签: c segmentation-fault


【解决方案1】:

在这里:

str_array[i] = (char*) malloc(sizeof(char) * strlen(str_length));
                                             ^^^^^^^^^^^^^^^^^^
    strcpy(str_array[i],str_length); 

改成:

 str_array[i] = malloc(strlen(str_length)+1);
                                          ^^
    strcpy(str_array[i],str_length); 

满足对 NULL 字符的需求。
(注意,malloc() 的强制返回不是必需的,在 C 中通常不是一个好主意。根据定义,sizeof(char) is always 1`。)

【讨论】:

    【解决方案2】:
    str_array[i] = (char*) malloc(sizeof(char) * strlen(str_length));
    

    您还需要一个字符来容纳空终止字符。

            str_array[i] = malloc(sizeof(**str_array) * strlen(str_length) + 1);
            strcpy(str_array[i], str_length); 
    

    一些备注:

    1. 不要转换 malloc 的结果。如果代码无法编译,则使用 C++ 编译器编译 C 代码,这是不好的。
    2. sizeof 中使用对象而不是类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多