Search code examples
cvisual-studio-codegcccs50

When I run/debug C program, malloc() seems to be assigning "r\r\r\r\r\r..." to a pointer and I am not sure why?


I am working through the Harvard cs50x courses and I have purposefully been avoiding using their cs50.h library so that I don't have another hoop to jump through re-learning how to code certain things in C.

Here is my code:

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

It's purpose is to get input from the user as a string, then parse that information to provide a reading level.

**The Issue: ** I am able to run and debug this code on cs50.dev, and it appears to work exactly as I intended. The very first line of main() sets the text variable, per my image below:

text: 0x55ed3e7412a0 "" / *text: 0 '\000'

However, trying to run/debug on my local Windows machine results in the text variable being set per below:

text: 0x7416e0 "\r\r\r\r\r..." / *text: 13 '\r'

I don't understand why this is happening, and I am not sure where to even start looking. Obviously it has something to do with the malloc() function, but i dont understand what it could be allocating that is different from what it allocates on cs50.dev.

I imagine this is an issue with my setup of VScode, or possibly my setup of MinGW? Any assistance here is greatly appreciated. Any additional comments on how to improve my code as well would be appreciated.


Solution

  • You wrongly assume that the memory allocated by malloc is zeroed. In fact, its content is not determined and you have entered the unchartered area of Undefined Behaviour . It is why you are getting different content of the allocated block when compiled and run using different compilers.

    If you want to have it zeroed:

     char *text = calloc(100,1);