0

In file count.c, program reads a string from a file and then counts the total number of characters given in the file. Following are the lines of code in file count.c:

#include <stdio.h>
int main()
#define max 1000
{
    char c, inpt[max];
    int i;
    for (i=0; (c=getchar()) !='\n'; ++i){
        inpt[i]=c;
    }
    printf("Count is %d. ",i);
}

Code compiles successfully without any error messages but when I run command:

    count.exe < Rehan.txt

Program crashes saying 'count.exe has stopped working'.

Problem details are:

    Problem signature:
    Problem Event Name: BEX
    Application Name:   count.exe
    Application Version:    0.0.0.0
    Application Timestamp:  53e5d5d5
    Fault Module Name:  StackHash_e98d
    Fault Module Version:   0.0.0.0
    Fault Module Timestamp: 00000000
    Exception Offset:   ffffffff
    Exception Code: c0000005
    Exception Data: 00000008
    OS Version: 6.1.7600.2.0.0.256.1
    Locale ID:  1033
    Additional Information 1:   e98d
    Additional Information 2:   e98dfca8bcf81bc1740adb135579ad53
    Additional Information 3:   6eab
    Additional Information 4:   6eabdd9e0dc94904be3b39a1c0583635
doniyor
  • 36,596
  • 57
  • 175
  • 260

3 Answers3

1

If your file has a single line, your program will loop forever, also, check for i < max - 1, try:

for (i = 0; i < (max - 1) && (c = getchar()) != EOF && c != '\n'; ++i)
{
    inpt[i] = c;
}

And what about the trailing 0? NUL terminate inpt if you want a valid string:

inpt[i] = '\0';
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

That's a buffer overflow exception. Apparently Rehan.txt is a file without a '\n' character in the first 1000 characters, so the loop tries to write inpt[i] for values of i larger than 999. You can prevent this from happening by checking for EOF instead, as well as a i < 1000 condition, so that you don't get the same error for files that are larger than your buffer.

Finally, if that's all this program needs to do, consider eliminating inpt altogether. Your code writes to this buffer but doesn't read from it.

Chris Culter
  • 4,470
  • 2
  • 15
  • 30
  • `i < 1000` isn't giving the correct output while EOF is. Thanks for the clear explanation. –  Aug 09 '14 at 09:35
1

1.- The file has no \n

2.- The file length is longer than 1000

You should take care the program doesn't arrive to the end of file.

Your program remade.

#include <stdio.h>
int main()
#define max 1000
{
    char c, inpt[max];
    int i;
    bool bEnd=false;
    for (i=0; !bEnd; i++)
    {
        c=getchar();
        if(c=='\n' || c==EOF)
        {
            inpt[i]=0;
            bEnd=true;
        }
        else
        {
            inpt[i]=c;
        }
    }
    printf("Count is %d. ",i);
}
Husita
  • 24
  • 4