Rayne
Rayne

Reputation: 14997

strcpy not copying the full string

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.

Upvotes: 1

Views: 1886

Answers (1)

jcoder
jcoder

Reputation: 30055

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);

Upvotes: 0

Related Questions