由于这 1 行代码,我一直在拔头发。如果我不为额外的内存动态分配内存(仅通过 char extra[*cur_size+1];),vsprintf 就会卡住。
char *append(char *str, int *cur_size, char *fmt, ...) {
va_list args;
va_start(args, fmt);
int len = vsnprintf(NULL, 0, fmt, args) + strlen(str);
if (len > *cur_size) {
//alloc more memory
*cur_size = len * sizeof (char) << 1;
char *extra = malloc(*cur_size+1);
// char extra[*cur_size+1]; will cause problem
strcpy(extra, str);
str = extra;
}
vsprintf(eos(str), fmt, args);
va_end(args);
LOGE("len = %d, cur_size = %d", len, *cur_size);
return str;
}