0

I want bug variable to be dynamic and depending upon sizeof(cmd+args) passed to it

void excmd(const char* cmd, ...) { char buf[100]; // I want it to be dynamic like size of(cmd+args) va_list args; va_start(args,cmd); vsnprintf(buf,sizeof(buf),cmd,args); system(buf); va_end(args); } 
10
  • This looks like an XY problem. What actual problem are you trying to solve? Commented Feb 13, 2019 at 14:03
  • 1
    I recommend e.g. this vprintf (and family) reference. Pay close attention to what the vsnprintf function returns, especially if the buffer is a null pointer and the size is zero. Commented Feb 13, 2019 at 14:03
  • I need buf variable to be Dynamic it's hard to guess how long user gives the input string like a path to a file or something Commented Feb 13, 2019 at 14:05
  • @XeXkek Some programmer dude's comment is almost the answer you're looking for. Commented Feb 13, 2019 at 14:06
  • When I use char *but, and use vsprintf to not include passing sizeof buffer than program crashes and sends signal SIGSEGV Commented Feb 13, 2019 at 14:12

1 Answer 1

3

You probably want something like this:

void excmd(const char* cmd, ...) { char *buf = NULL; va_list args; va_start(args, cmd); int sizeneeded = vsnprintf(buf, 0, cmd, args) + 1; va_end(args); buf = malloc(sizeneeded); va_start(args, cmd); vsnprintf(buf, sizeneeded, cmd, args); va_end(args); system(buf); free(buf); } 

or

void excmd(const char* cmd, ...) { va_list args; va_start(args, cmd); int sizeneeded = vsnprintf(NULL, 0, cmd, args) + 1; va_end(args); char buf[sizeneeded]; va_start(args, cmd); vsnprintf(buf, sizeneeded, cmd, args); va_end(args); system(buf); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Nice one but one correction that's this should be int sizeneeded = vsnprintf(NULL, 0, cmd, args)+1; to also reserve space for terminator
@XeXkek you're right, answer edited. You can remove the comments. Thanks.
As an optimization, you can make the first call to vsnprintf() with a fixed-size buffer, something like 512, 1024, or maybe even 4096 bytes. That way, if it does fit, you don't have to allocate memory and make the vsnprintf() call a second time. You might as well use the results of the first call if you can do so without doing it again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.