我收到此分段错误(核心转储)错误。有谁知道为什么?

时间:2020-05-22 14:10:46

标签: c malloc

基本上,我的项目是查找我输入的字符串有多少个元音和常量。但这不起作用,我也不知道为什么。我检查了CREATE TABLE #data_result ( id INT, ord_dt DATE, sell_dt DATE, flag VARCHAR ); INSERT INTO #data_result SELECT id , ord_dt , sell_dt , Iif(sell_dt = ord_dt OR DateDiff(DAY, ord_dt, sell_dt) = 4 OR DateDiff(DAY, sell_dt, ord_dt) = 1, 'Y', 'N') FROM #data; SELECT * FROM #data_result; 是否有效,但是我猜它可以正常工作。

这是我的代码:

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;
}

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个问题:

  • gets(string)尝试将输入读入无效地址,因为string是未初始化的指针。您应该传递一个数组。
  • gets是一个过时的函数,不能安全使用。您应该改用fgets()
  • 辅音的数量不是(26 - number_of_vowels)。您应该计算字母的数量并减去元音的数量。
  • 使用诸如'A'之类的字符常量比诸如65之类的实际ASCII代码更具可读性和可移植性。

这是修改后的版本:

#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;
}