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.

3
  • If you are using C++, why are you still using char [] and FILE instead of std::string and streams? Commented Nov 15, 2012 at 10:46
  • I'm more familiar with char[] and FILE. Would this have made a difference? Commented Nov 16, 2012 at 0: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. Commented Nov 16, 2012 at 5:01

1 Answer 1

0
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); 
Sign up to request clarification or add additional context in comments.

1 Comment

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".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.