cstringinputinvalid-characters

C user input sporadic invalid results


Coding in C, I'm having an issue with user input. Sometimes, the input works and sometimes it doesn't.

Example run output from terminal:

dennis@MBP2021 Encryption % make
cc Gronsfeld_Cipher.c /Users/dennis/Documents/C/programs/DJSlibrary/cs50.c -o cipher
dennis@MBP2021 Encryption % ./cipher 

Please enter line to be encoded: This, however, is not the time.

You entered: This, however, is not the time. Length: 31

The message is:  This, however, is not the time.
The cipher is:   EZNH, SCVKOHZ, KF UFP GXF ONWX.
The decipher is: THIS, HOWEVER, IS NOT THE TIME.


dennis@MBP2021 Encryption % ./cipher

Please enter line to be encoded: This, however, is not the time, nor the place to have fun.

You entered: This, however, is not the time, nor the place to have fun. Length: 58
zsh: trace trap  ./cipher
dennis@MBP2021 Encryption % 

code snippet:

char data[] = "Dummy";
int keys[] = {11, 7, 13, 10, 25, 9, 8, 3};  


// Do the stuff
int main(void)
{   
    // Get input from user
    char *string_input = NULL;
    size_t string_size = 250;
    ssize_t bytes_read;

    printf("\nPlease enter line to be encoded: ");
    string_input = (char *) malloc(string_size);
    bytes_read = getline(&string_input, &string_size, stdin);

    if(bytes_read < 2)
    {
        printf("\n\nNo input was entered. Program terminating.\n");
        printf("Error Code: 1\n\n");
        free(string_input);
        return 1; 
    }

    string_input[bytes_read-1] = 0; // Clear out the new line.
    
    printf("\nYou entered: %s Length: %ld\n", string_input, bytes_read-1);
    strcpy(data, string_input);
    free(string_input);

    // Get sizes
    int DataLen = strlen(data);
    int ks = sizeof(keys) / sizeof(keys[0]);

    printf("\nThe message is:  %s", data);

According to what I see on the terminal, it dies at the strcpy (I guess) The line string_input[bytes_read-1] = 0; // Clear out the new line is trying to remove the line feed at the end of the string input. It never gets to the last printf. I don't understand why it worked with a small line (31 bytes) and not the 58 byte line. I tried to use debug in vscode, but it doesn't allow me to enter an input line. Something else I need to find out. Also, I'm new to C programming. Thanks in advance.


Solution

  • The problem is very likely this statement:

    strcpy(data, string_input);
    

    Here you copy data into an array that can only hold six characters, null-terminator included.

    When you create and initialize the data array you only make space for the string "Dummy", nothing more.

    If the input it longer than five characters, then that means you will write out of bounds of data, and have undefined behavior.

    Set a specific size for the data array, one that is big enough to hold the largest input.

    Or keep on using string_input, and don't use data at all.