-1

I have a peculiar problem in Linux2.4, C and using gcc.

There is a small program to retrieve information from a file using cat & grep cmd.

#define tmpFile "/tmp/cli_tmp_file.txt"
#define MAX_CMD 50

void getRange()
{
        char cmd[MAX_CMD+1];

        // remove the temp file first
        snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
        system(cmd);
        // create temp file
        snprintf(cmd, MAX_CMD, "touch %s",tmpFile);
        system(cmd);
        // execute the command
        snprintf(cmd, MAX_CMD, "echo \"Range:Max val 500\" > %s",tmpFile);
        system(cmd);
        // dump out the temp file so user could see
        snprintf(cmd, MAX_CMD, "cat %s|grep \"Range\"", tmpFile);
        system(cmd);
        // remove the temp file
        snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
        system(cmd);
}

when i execute this code, i get output as cat: /tmp/cli_tmp_file.txt: No such file or directory

However, the file is created in the tmp folder with the contents

# pwd
/tmp
# ls -l
-rw-r--r--    1 root     root           68 Oct 10 12:54 cli_tmp_file.txt

#more /tmp/cli_tmp_file.txt
Range:Max val 500

On manual execution of the same cmd, it displays the intended output

# cat /tmp/cli_tmp_file.txt|grep Range
Range:Max val 500

Any help would be appreciated. Thanks in advance.

UserM
  • 190
  • 2
  • 19
  • 2
    You should check the return value of `system` to see if the commands succeed. Also, try printing the `cmd` buffer after each `snprintf` to see if it contains the intended command. – Fred Foo Oct 10 '13 at 13:36
  • remove the file, try again. – Karoly Horvath Oct 10 '13 at 13:40
  • Avoid using `system` with `rm`; consider calling [remove(3)](http://man7.org/linux/man-pages/man3/remove.3.html) function. And to create a file, just `fopen` it for writing and `fclose` it just after. Don't forget to test against failure of every function. – Basile Starynkevitch Oct 10 '13 at 13:42
  • 1
    Is there a reason you aren't just writing this as a shell script? It would be a bit simpler... – twalberg Oct 10 '13 at 14:05

1 Answers1

1

It's a (managed, but ignored) buffer overrun, the echo command is more than 50 characters. The command is truncated by snprintf() but you run it anyway. Check return values!

unwind
  • 391,730
  • 64
  • 469
  • 606