Prevent a file path buffer overrun

If a filename passed from the command line arguments is ever longer than
the current working directory (and it usually is longer), strcpy will
overrun the working directory buffer. This usually doesn't cause a crash
right away, but it caused weird bugs for me, like an assertion failure
in free() when trying to free the buffer later:

    free(): invalid next size (fast)

Valgrind helped me track down the cause:

    $ valgrind bin/grafx2-sdl ~/Projects/kind-of-longish-directory-name/file.gif

    ...

    ==116375== Invalid write of size 1
    ==116375==    at 0x483DDE6: strcpy (vg_replace_strmem.c:511)
    ==116375==    by 0x1265B2: Init_program (main.c:1104)
    ==116375==    by 0x12704F: main (main.c:1536)
    ==116375==  Address 0x5534a81 is 21 bytes after a block of size 28 alloc'd
    ==116375==    at 0x483CD7B: realloc (vg_replace_malloc.c:834)
    ==116375==    by 0x4E70F3F: getcwd (in /usr/lib/libc-2.32.so)
    ==116375==    by 0x17277E: Get_current_directory (io.c:1096)
    ==116375==    by 0x125B02: Init_program (main.c:655)
    ==116375==    by 0x12704F: main (main.c:1536)
This commit is contained in:
Jordan Christiansen 2020-12-15 12:06:34 -06:00
parent 6f94186caf
commit ff7e5c9ee2

View File

@ -1101,7 +1101,8 @@ int Init_program(int argc,char * argv[])
// backups
if (file_in_command_line > 0 && directories[0] != NULL)
{
strcpy(Main.selector.Directory, directories[0]);
free(Main.selector.Directory);
Main.selector.Directory = strdup(directories[0]);
}
// Test de recuperation de fichiers sauvés