1

I'm using Visual C++ 6.0, and I have the code below.

char filename[1000], string[5];
FILE *fin;
strcpy(filename, argv[3]);
if ((fin = fopen(filename, "r")) != NULL)
{
    fgets(string, 100, fin);
    string[strlen(string)-1] = NULL;
    printf("filename = %s\n", filename);
    printf("argv[3]= %s\n", argv[3]);
    printf("string = %s\n", string);
}

argv[3] is the full path and filename, e.g. C:\Users\Desktop\file.txt, and the content of the file is

1
2
3

So "1" should be stored in the "string" variable.

However, for about 1 out of 4 runs, I would get the output

filename = C:\Users\Desktop\file.tx
argv[3] = C:\Users\Desktop\file.txt
string = <very long garbage value>

Why did

strcpy(filename, argv[3]); 

not copy the entire string, missing the last "t"? And why is fin not NULL in this case, since the file should not have existed?

I should also add that this code exists in a multi-thread program, but only 1 thread executes this code.

Rayne
  • 14,247
  • 16
  • 42
  • 59
  • If you are using C++, why are you still using `char []` and `FILE` instead of `std::string` and streams? – DCoder Nov 15 '12 at 10:46
  • I'm more familiar with char[] and FILE. Would this have made a difference? – Rayne Nov 16 '12 at 00:55
  • Yes, it would have. `std::string`, like most other `std` containers, expands automagically to contain all the data you put into it, saving you from having to track lengths and memory allocation manually. – DCoder Nov 16 '12 at 05:01

1 Answers1

1
string[5];

You have only allocated enough space for 4 characters and a null terminator but your fgets is reading up to 100.

fgets(string, 100, fin);
jcoder
  • 29,554
  • 19
  • 87
  • 130
  • Yes, but wouldn't fgets also read up to the \n, which the file has after the "1". Anyway, this line comes after the strcpy, which I believe is the main problem for the garbage value I'm getting for "string". – Rayne Nov 16 '12 at 00:56