Mic*_*bro 2 c string malloc realloc
我有格式字符串,我解析它比用输入参数替换格式说明符.现在我考虑如何在替换参数后为这样的结果字符串分配内存.我可以像格式字符串一样分配这个字符串,但是在%s任何长的位置替换其他字符串
都需要在某些不确定的融合中重新分配这个字符串,这使得有必要在代码中进行一些不优雅的计算.所以我认为我可以分配这个从格式字符串创建的字符串,只需char by char,每次重新分配它,如:
/*** for loop traversing next chars in format string ***/
// if new char
str = realloc(str, sizeof(*str) +1);
// if %s
str = realloc(str, sizeof(*str) + strlen(in_str));
// if %d
str = realloc(str, sizeof(*str) + strlen(d_str));
Run Code Online (Sandbox Code Playgroud)
通常内部库代码处理可变字符串/数组/列表/其他任何其他2 ^ n步骤的长度 - 即当你有4个字节的内存并需要分配5时,它实际上分配8.这将减少数量对于~log(n)操作,realloc()调用很昂贵.但是,可能还有其他优化,具体取决于库.