Home > Net >  My code runs smoothly to the end in Linux but ends abruptly in Windows
My code runs smoothly to the end in Linux but ends abruptly in Windows

Time:05-14

I am new to coding. As a practice problem, I wrote a program to sort strings as alphabetically, as in a dictionary. My program takes as input: (a) The number of strings the user has in mind and (b) The strings, one by one, each terminated by pressing the enter key. It stores the initial input in a buffer array of size MAXSTR and simultaneously counts the number of characters. Then it creates allocates memory of requisite size at memory location input[i] and copies the buffer to that location. It also creates an index array, with array elements having value of 0, 1, 2 ... each corresponding to one the 0th string, 1st string, 2nd string ... and so on. The function dictsort sorts the index array based on the alphabetical position of the corresponding string. My program runs smoothly on Linux machines. However, on Windows, it compiles alright, but while running the executable, it ends abruptly while executing the line "input[i]=(char)malloc(jsizeof(char));". If any of you guys can indicate what is happening it will be of great help. Note that my problem is with the main function only. The sorting functions work fine, and hence those are not either included or commented out from below code.

#define MAX 10000
#define MAXSTR 100
#include<stdio.h>
#include<stdlib.h>
//int dictsort(char **mainarray, size_t *indexarray, size_t elementcount);
//int strcompare(char* str1, char* str2);
//int getvalue(int input);

int main(void){
    size_t n, i, j,k;
    char buffer[MAXSTR];
    int c;
    size_t *index;
    char **input;
    printf("Input number of elements:\t");
    scanf("%ld", &n);
    n=n<MAX ? n : MAX;
    index=(size_t*)malloc(n*sizeof(size_t));
    getchar(); // flush the newline after scanf

    for(i=0;i<n;  i){
        index[i]=i;
        printf("Input element %ld:\t", i 1);
        j=0;
        while(((c=getchar())!=EOF) && (c!='\n') && (c!='\0') && (j<MAXSTR-1)){
            buffer[j]=c;
              j;
        }
        buffer[j]='\0';
                              printf("Upto 1\n"); //program comes upto here
        input[i]=(char*)malloc(j*sizeof(char));
                              printf("Upto 2\n"); //never reaches here
        for(k=0;k<j 1;  k){
            input[i][k]=buffer[k];
        }
        
    }

    //dictsort(input, index, n);        //disabled for debugging

    printf("The sorted array is: \n");
    for (i=0;i<n;  i){
    printf("%s  ", input[index[i]]);
    }

    for(i=0;i<n;  i){
        free(input[i]);
    }

    free(index);

    return 0;
}

CodePudding user response:

First error:

You are allocating memory for index and input[i], but not for input itself. This means that you are dereferencing an uninitialized pointer on the following line:

input[i]=(char*)malloc(j*sizeof(char));

This will invoke undefined behavior, which explains why it crashes on that line on one platform, but works on another platform.

Second error:

The line

input[i]=(char*)malloc(j*sizeof(char));

will not allocate sufficient space for storing the string. Since j is the size of the string without the terminating null character, you must allocate j 1 bytes instead.

Due to not allocating a sufficient number of bytes for the string, the following loop will access the memory buffer input[i] out of bounds:

for(k=0;k<j 1;  k){
    input[i][k]=buffer[k];
}

This will invoke undefined behavior.

Third error:

Another source of undefined behavior in your program is the following line:

scanf("%ld", &n);

The correct conversion format specifier for size_t is %zu, not %ld. See the documentation of the function scanf for further information.

On 64-bit Microsoft Windows, a long has a width of 4 bytes, but a size_t has a width of 8 bytes. Therefore, because you are using the format specifier for long instead of size_t, the function scanf is probably only writing to half of the variable n, leaving the other half of the variable uninitialized. This is likely to cause trouble when you read the value of n later in the program.

Most compilers will warn you about using the wrong scanf conversion format specifiers, assuming that you enable all compiler warnings. You may want to read this:

Why should I always enable compiler warnings?

  • Related