malloc - Strange behavior (SEGFAULT) of a C program using stdargs (va_start) -


I have written a variadic C function, which is to allocate the memory required for the buffer of the mission, and then the given argument Function in buffer but I'm seeing a strange behavior with it, it only works once if I have two calls for this function, then it is segfaults.

  #include & lt; Stdio.h & gt; #include & lt; String.h & gt; # Include & lt; Stdlib.h & gt; # Include & lt; Stdarg.h & gt; Char * xsprintf (char * fmt, ...) {va_list ap; Four * parts; Four * buf; Size_t len ​​= strlen (fmt) +1; Va_start (AP, FMT); While (part = va_arg (ap, four *)) len + = strlen (part); Va_end (ap); Buf = (four *) molk (size (four) * lane); Va_start (AP, FMT); Vsprintf (buff, fmt, ap); Va_end (ap); Return buff; } Int main (int argc, const char * argv []) {char * b; B = xsprintf ("My favorite fruits are:% s,% s, and% s", "coffee", "c", "oranges"); Printf ("Size De Buff% d \ n", is Stellon (B)); // this work After that, it segfaults / * free (b); B = Null; * / B = xsprintf ("My favorite fruits are:% s,% s, and% s", "coffee", "c", "oranges"); Printf ("Size De Buff% d \ n", is Stellon (B)); Printf ("% s", b); Return 0; }  

Here is the output of this program:

  Size de buf 46 [1] 4305 segmentation error ./xsprintftest  

Am I doing something wrong? Have I not used va_start in a function multiple times? Do you have any options? Thanks a lot! :)

You should use vsnprintf . Use this twice to know the length of the buffer with the NULL destination / zero size that you need to allocate, the second time to fill the buffer. This way your function will work, even if not all logic strings.

In the written form, if any non string argument (% d , % X , % f , etc.) . And the number of characters in the % is not a valid way of obtaining the number of arguments. Your result may be too high (if any letter % letter is encoded as %% ) or too little (even if % * S , %. * D * / code>, etc. width / exact specification).


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -