我得到了这个Segmentation fault(core dumped)错误。有人知道原因吗?

问题描述 投票:0回答:1

基本上,我的项目是用来查找我输入的一个字符串有多少元音和常量。但它不工作,我不知道为什么。我检查了 malloc 工作,但它的工作发现我猜。

这是我的代码。

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

#define E_A_LETTERS 26

int check_vowels(char *p_string);

int main(void) {
    // Here your code !
    char *string;
    int vowels;
    int constants;

    printf("Enter a string: ");
    gets(string);

    string = (char *)malloc(strlen(string) * sizeof(char));
    if (string == NULL) {
        printf("Unable to allocate memory...");
        exit(0);
    }
    vowels = check_vowels(&string[0]);
    constants = E_A_LETTERS - vowels;

    printf("\nNumber of vowels : %d", vowels);
    printf("\nNumber of constants : %d\n", constants);
    free(string);
}

int check_vowels(char *p_string) {
    int i = 0;
    int count = 0;
    while (1) {
        if(*(p_string + i) == 65 || *(p_string + i) == 69 || *(p_string + i) == 73 || *(p_string + i) == 79 || *(p_string + i) == 85)
            count++;
        if(*(p_string + i) == 97 || *(p_string + i) == 101 || *(p_string + i) == 105 || *(p_string + i) == 111 || *(p_string + i) == 117)
            count ++;
        if(*(p_string + i) == '\0')
            break;
        i++;
    }
    return count;
}

输出示例 - 错误 :

Enter a string: apples
Segmentation fault (core dumped)
c malloc
1个回答
0
投票

你的代码中存在多个问题。

  • gets(string) 试图把输入的内容读到一个无效的地址中去 string 是一个未初始化的指针。你应该传递一个数组。
  • gets 是一个过时的函数,不能安全使用。你应该使用 fgets() 而不是。
  • 辅音的数量不 (26 - number_of_vowels). 你应该计算字母的数量,并减去元音的数量。
  • 使用字符常量,如 'A' 比实际的ASCII码如 65.

这里是一个修改版。

#include <stdio.h>

int count_vowels(const char *p_string);
int count_letters(const char *p_string);

int main(void) {
    char string[100];
    int vowels;
    int constants;

    printf("Enter a string: ");
    if (fgets(string, sizeof string, stdin) == NULL) {
        printf("No input\n");
        return 1;
    }
    vowels = count_vowels(string);
    constants = count_letters(string) - vowels;

    printf("Number of vowels: %d\n", vowels);
    printf("Number of constants: %d\n", constants);

    return 0;
}

int count_vowels(const char *p) {
    int count = 0;
    for (int i = 0; p[i] != '\0'; i++) {
        if (p[i] == 'A' || p[i] == 'E' || p[i] == 'I' || p[i] == 'O' || p[i] == 'U')
            count++;
        if (p[i] == 'a' || p[i] == 'e' || p[i] == 'i' || p[i] == 'o' || p[i] == 'u')
            count++;
    }
    return count;
}

int count_letters(const char *p) {
    int count = 0;
    for (int i = 0; p[i] != '\0'; i++) {
        /* assuming A-Z and a-z are contiguous, as is the case in ASCII */
        if ((p[i] >= 'A' && p[i] <= 'Z') || (p[i] >= 'a' && p[i] <= 'z'))
            count++;
    }
    return count;
}
© www.soinside.com 2019 - 2024. All rights reserved.