想要实现一个功能,即给一个字符串扩容,我想出的代码如下:
#include<iostream>
using namespace std;
int main() {
char *s="\0";
int n = strlen(s);
float x = 4.5;
char buf[64];
sprintf(buf, "%.2f\0", x);
s = (char*)realloc(s, sizeof(char)*(n + strlen(buf) + 1));
strcat(s, buf);
system("pause");
}
我想先定义一个空字符串s,然后使用sprintf把数字转换为字符串,然后重新分配内存,再把原来的和数字字符串连接起来,不过程序报错,也没看出来vs提出了什么错误。
先多谢大神指教!
realloc内部会free(s), free一个不由malloc分配的内存是未定义行为。一般会segfault。
如果你不是用windows,这个问题可以用valgrind检查。我不知道vs能不能检查这个。