-1

So I have this function that goes as follows f(char * str). The string argument is a file name that is accessed using another function. So if I do f("grille1.txt") the program works as expected. However, if I do

char * filename;
scanf("%s", filename);
f(filename);

the program doesn't work as expected. So I concluded that the issue is with the scanf. However I tried doing

printf("%d Are they equal?", !strcmp(filename, "grille1.txt"));

and I get a 1 as a result which means that they are indeed equal so what could the issue be that results in using the variable filename not giving the same results as manually using "grille1.txt"?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Motcho
  • 3
  • 2
  • 1
    What do you expect to happen after the user input? Sidenote: `scanf("%s",filename);` is unsafe. Don't. – Ted Lyngmo Oct 30 '21 at 22:09
  • 1
    What's your understanding of the line `char * filename;`? – Passerby Oct 30 '21 at 22:10
  • 3
    The compiler should be warning you that `scanf("%s",filename);` is using an *uninitialised pointer*. That is, there is no memory allocation. – Weather Vane Oct 30 '21 at 22:10
  • The behaviour you observe with [`strcmp`](https://en.cppreference.com/w/c/string/byte/strcmp) is undefined, because that function expects null terminated strings, and you have passed in an unknown string (`filename`) as one of the parameters – smac89 Oct 30 '21 at 22:19

1 Answers1

2

The function scanf requires the address of a sufficiently large memory location where it should write the string, and you are supposed to pass the address of that memory location as a parameter to scanf. However, you are instead passing an uninitialized (garbage) value. This causes undefined behavior.

Therefore, I suggest that you change the lines

char * filename;
scanf("%s",filename);
f(filename);

to:

char filename[100];
if ( scanf( "%99s", filename ) == 1 )
    f( filename );

In the code above, the declaration

char filename[100];

will allocate an array of 100 characters, which is sufficient to store 99 characters and the terminating null character. When passing filename to scanf, the array will decay to a pointer to the address of the first character of the array.

I enclosed the scanf function call inside an if statement, because it is generally a good idea to check the return value of scanf, to make sure that the function was successful.

Also, I am using the %99s format specifier instead of %s to limit the input to 99 characters, otherwise a buffer overflow would occur if the user enters more than 99 characters.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Definite kudos for pointing out `"%s"` is no safer than `gets()` unless the *field-width* modifier is used to prevent overflow. – David C. Rankin Oct 31 '21 at 00:23