简体   繁体   中英

variable argument function in C

I have a variable list function

/* vsprintf example */
 #include <stdio.h>
 #include <stdarg.h>

 void PrintFError (char * format, ...)
 {
    char buffer[50];
    va_list args;
    va_start (args, format);
    vsprintf (buffer,format, args);
    perror (buffer);
    va_end (args);
 }

 int main ()
 {
     FILE * pFile;
     char szFileName[]="myfile.txt";
     int firstchar = (int) '#';

     pFile = fopen (szFileName,"r");
     if (pFile == NULL)
        PrintFError ("Error opening '%s'",szFileName);
     else
     {
        // file successfully open
        fclose (pFile);
     }
     return 0;
 }

In above example how can we check the received message in "PrintError" function that we are not crossing the buffer size in this example 50 while using "vsprintf" in above example. This should be achieved in portable way.

您应该使用更安全的vsnprintf,并将其限制为最多50个字符。

int vsnprintf(char *str, size_t size, const char *format, va_list args);

You are correct to worry about buffer overflow. You can't do this with vsprintf, but you can with vsnprintf , which includes an argument which is the length of the buffer.

You can use vsnprintf . This is, strictly speaking, non-standard unless you have a C99 compiler, but is supported on most environments. If you do not have an implementation of vsnprintf on your platform, you can simply add a portable implementation to your program.

Use vsnprintf() . It allows you to specify the number of characters to output ( n ):

int vsnprintf(char *s, size_t n, const char *format, va_list ap);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM