c - va_list and char* strings -


[edit] inserted null terminated in samples

i have function receives va_list ends null. concatenate each string in char* called joinedstring. function works expected except joinedstring grows size each time call function. mean previous string remains , new string joined.

example: first call:

showmsg(style1, "a", "s", "d", null); 

yielded result: "asd"

second call:

showmsg(style1, "w", "w", "q", null); 

yielded result: "asdwwq"

this behaviour strange because each time function called joinedstring initialized. va_list holds values used? i'm using c, not c++ , know, using std::string far more easy.

int showmsg(msgboxstyle msgstyle, char* str, ...) {     char* title = "", *joinedstring = "", *thearg = "";     wchar_t* convertedtitle = "", *convertedstring = "";      va_list args;     thearg = str;     va_start( args, str );         while(thearg != null)         {             if(msgstyle == warn)             {                 title = thearg;             }             else             {                 strcat( joinedstring, thearg );                 strcat( joinedstring, "\n\r" );             }             thearg = va_arg(args, char*);         }     va_end(args);     ...     convertedtitle = (wchar_t*)malloc((strlen(title)+1)*sizeof(wchar_t));     convertedstring = (wchar_t*)malloc((strlen(joinedstring)+1)*sizeof(wchar_t));     mbstowcs( convertedtitle, title, strlen(title)+1 );     mbstowcs( convertedstring, joinedstring, strlen(joinedstring)+1 );     ...     free(convertedtitle);     free(convertedstring); } 

that's because can't initialize strings that. initializer char* joinedstring = "" initializing pointer joinedstring point specific memory address @ beginning of program, consists of empty string.

then, first time call function, joinedstring set point still empty memory area. put characters there , exit.

next time start, characters still there. thing initialize pointer, not actual data. strcat appends new args end of filled string!

this should segfaulting, i'm pretty impressed program outputting anything. it's working because using few bytes, you're not overwriting much.

to fix it, initialized joinedstring malloc:

char* joinedstring = malloc(max_length * sizeof(*joinedstring)); joinedstring[0] = '\0'; // initialize empty string 

and @ end of function, free memory

free(joinedstring); 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -