0

I have written a function to process a variadic input arguments like below -

std::string ReturnMessage(const char * format, ...)
{
    va_list vl;
    va_start(vl, format);

    std::stringstream ss;
    for(int i = 0; format[i] != '\0'; ++i)
    {
        switch(format[i])
        {
            case 's':
            {
                char *str = NULL;
                str = va_arg(vl, char *);

                if(*str)
                {                   //Getting memory access violation here
                    ss << str;
                }
            }
                break;
        }
    }
    val_end(vl);
    return ss.str()
}

No when user assigns non string value(ReturnMessage("%s %s","Testing",100)) as string and at that str gets assigned to Bad Pointer and if(*str) statement throws Access Violation exception which is valid here. But How can I prevent invalid string to get added into stringstream??

Caesar
  • 9,483
  • 8
  • 40
  • 66
user987316
  • 894
  • 4
  • 13
  • 35
  • 1
    Just leave it as *undefined behaviour*, just like the C++ standard library. – Bathsheba Dec 23 '13 at 08:46
  • 1
    `varargs` aren't type-checked and _can't_ be type-checked. @Bathsheba has the right sentiment here. C gave you enough rope that you could shoot yourself in the foot with it. C++ allows you to redefine what rope, shoot and foot mean in the process. – Joe Z Dec 23 '13 at 08:52
  • Can you guys please elaborate it more.. – user987316 Dec 23 '13 at 08:55
  • 2
    If its possible to better state "varargs aren't type-checked and can't be type-checked." I can't think of how. You're invoking functionality expecting data of a specific type, then flatly ignoring that type-requirement and providing something else. Since the provided arguments aren't checked at compile-time, you're thus invoking undefined behavior. And that is honestly the best I can do. – WhozCraig Dec 23 '13 at 09:03
  • Please refer the following link. http://stackoverflow.com/questions/205529/c-c-passing-variable-number-of-arguments-around – Ashok Chellappan Dec 23 '13 at 09:05
  • 1
    @JoeZ "C gave you enough rope that you could shoot yourself in the foot with it". How in the world can you shoot yourself with a rope ?! – Drax Dec 23 '13 at 09:13
  • 1
    @Drax: "Enough rope to shoot yourself in the foot with" a joke I've heard repeated since the 90s. Basically, the idea is that C (and C++) let you mix types and programming metaphors in dangerous ways. When it works, great. When it doesn't work, things can go horribly wrong. The saying itself comes from "enough rope to hang your self" and "don't shoot yourself in the foot." With UB, you think you're tying a knot in the rope, but you end up with a bullet in your foot. And, apparently, someone even wrote a book with that title; I just remember seeing the phrase on USENET or something. – Joe Z Dec 23 '13 at 16:06

0 Answers0