当我运行/调试 C 程序时,malloc() 似乎正在分配“r ...”到一个指针,我不知道为什么?

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

我正在学习哈佛 cs50x 课程,并且我有目的地避免使用他们的 cs50.h 库,这样我就没有另一个障碍来重新学习如何用 C 编写某些东西。

这是我的代码:

int main(void){
    // Prompt to enter text & allocate memory for string of 100 char
    char *text = malloc(100 * sizeof(char));
    printf("Enter Text: ");
    fgets(text, 100, stdin);

    // Calculate index
    int number_of_words = countWords(text);
    int number_of_letters = countLetters(text);
    int number_of_sentences = countSentences(text);

    float L = (float) number_of_letters / number_of_words * 100.0;
    float S = (float) number_of_sentences / number_of_words * 100.0;

    float index = 0.0588 * L - 0.296 * S - 15.8;

    // Print index from if > 1 "less than 1" and if greater that 16 "16+" else print index
    if (index < 1){
        printf("Reading Level: Before Grade 1\n");
    }
    else if (index > 16){
        printf("Reading Level: Grade 16+\n");
    }
    else{
        printf("Reading Level: Grade %i\n", index);
    }
    // Free memory and terminate program
    free(text);
    return 0;
}


// Count functions use a while loop to iterate through each char and count then return total count as int
// Removed due to Stack Overflow saying i have too much code in post

其目的是以字符串形式获取用户输入,然后解析该信息以提供阅读级别。

**问题:** 我能够在 cs50.dev 上运行和调试此代码,并且它似乎完全按照我的预期工作。 main() 的第一行设置文本变量,如下图所示:

text: 0x55ed3e7412a0

但是,尝试在我的本地 Windows 计算机上运行/调试会导致按以下方式设置文本变量:

text: 0x7416e0

我不明白为什么会发生这种情况,我什至不知道从哪里开始寻找。显然它与 malloc() 函数有关,但我不明白它可能分配的内容与它在 cs50.dev 上分配的内容不同。

我想这是我的 VScode 设置的问题,或者可能是我的 MinGW 设置的问题?非常感谢这里的任何帮助。对于如何改进我的代码的任何其他评论也将不胜感激。

c visual-studio-code gcc cs50
1个回答
0
投票

您错误地认为 malloc 分配的内存已归零。事实上,它的内容是不确定的,你已经进入了未定义行为的未知领域。

如果您想将其归零:

 char *text = calloc(100,1);
© www.soinside.com 2019 - 2024. All rights reserved.