Is it right to write like this ?:

void main() { char *path; scanf("%s", path); } 

In the dosovsky compiler (qc2) it works without problems, errors and errors. Yes, and the teacher said that the correct way to write than to create a static array.

There would be no questions if it were not for one bad luck. In the gcc compiler at this point the program is interrupted (segmentation error).

Here it is worth clarifying: the code above will also work in gcc, however, this code is no longer operational:

 void main() { char *path; int i; i = 0; scanf("%s", path); } 

Why is everything OK in the old compiler, but not in the modern one? Or is it wrong to write like that?


UPD 1:

@KoVadim , thanks, clarified.

@Janycz , in this case there seems to be no particular difference, dynamic or static, because the length of the string is unknown in advance.

And as a matter of fact, how in that case to read a line, not knowing its length? After all, to create a large array is unwise.

  • four
    char * path points to nowhere. It’s just that under the compiler it didn’t bother with the compiler, and you were lucky and wherever the path indicated was read / write accessible and safe. But it could indicate somewhere in a dangerous place. And then they would wonder for a long time why the system clock changes or the printer starts printing. Modern compilers are doing this. Conclusion. Teach to learn, the old compiler is simply not smart enough. - KoVadim
  • In C, you will have to create a large array. In C ++, you can not create a large array. - Janycz
  • @froxxendsg but no way. Allocate the buffer and carefully monitor that scanf does not cause an overflow (there is an opportunity to limit the size of the read line). Or do the reading itself character-by-character and allocate memory accordingly (though, all the same, the memory will need 2x the length of the read string) - gecube
  • @froxxendsg, in Linux in this situation, use ssize_t getline (char ** lineptr, size_t * n, FILE * stream); see man 3 getline . For Windows, write your analogue (a few dozen lines, good training). - avp
  • one
    Here's a little treatise on how to do it right: stackoverflow.com/a/4874163/276994 - VladD

1 answer 1

For the new compiler char *path; not a string, but a pointer to one character. Therefore, make a static array or use malloc : char *path = (char*)malloc(100);

  • For the old too. See the @KoVadim answer. - alexlz
  • one
    Well, not very good advice. The user will enter more than one hundred characters, and - bang! - stall disruption. Where do you think exploits come from? Here from this code. - VladD
  • @VladD, well, it is unlikely to fly out of the stack, but the structures in the heap will spoil with the following malloc / realloc / free (new / delete), and - bang! - segmentation fault. - avp
  • @avp: “bang!” is not in the sense of “the program will collapse”, but “out of the blue is a hole in security ”. - VladD