How to check in C, if an argument is a single character or a string of characters?

Viewed 84

let Suppose that I want to create a variadic function which has number of arguments as its first argument, and the other arguments are meant to be strings.

when I call my function with arguments of type strings, everything is fine since the function expects this type of data, but when I call it with a single character for example, BANG! bad move. suppose the program will sometimes receive unwanted arguments like this, How can I prevent this segmentation fault to happen. I wrote these code as an example:

#include <stdio.h>
#include <stdarg.h>
/* my variadic function to print strings arguments */
void args_printer(unsigned int args_number, ...)
{
    unsigned int index;
    char *arg_string;
    va_list arg_ptr;
    
    va_start(arg_ptr, args_number);
    for (index = 0; index < args_number; index++)
    {       
        arg_string = (char *)va_arg(arg_ptr, char *);
        if (arg_string != NULL)
            printf("%s ", arg_string);
        else    
            printf("Wrong data!\n");
    }        
    va_end(arg_ptr);
    
}

int main(void) {
    char *message = "Message : ";
    /*args_printer is working fine with correct data and NULL argument */
  args_printer(5, message, NULL, "La vie", " appartient", " au courageux!");
  
  /* arg_printer is having a segmentation fault once I enter this 'm' or a number */
  args_printer(4, 'm', "La vie", " appartient", " au courageux!");
    return 0;
}
1 Answers

How can I prevent this segmentation fault to happen.

Error checking: no-such-luck with a f(...) function.


Usually just code the m as a little string instead as char:

// args_printer(4, 'm', ...
args_printer(4, "m", ...

Alternative to form a string on the fly:

char ch = 'm';
...
// args_printer(4, ch, ...
args_printer(4, (char[2]){ch}, ...
Related