字符串 *char 与 malloc 动态内存分配连接错误
我想创建一个函数来连接字符串,它可以工作但它给出了一个错误并且处理器重新启动,我认为指针有问题,但我不知道它是什么,内存分配问题。
提前致谢!
char *buf;
int main(void) {
// ...
WriteString("#INIT.\r\n"); //serial output
buf = "";
while(1)
{
char *str1 = "qwe";
char *str2 = "asd";
char *str3 = "zxc";
char *str4 = "123";
buf = my_strcat(buf,str1);
buf = my_strcat(buf,str2);
buf = my_strcat(buf,str3);
buf = my_strcat(buf,str4);
WriteString(buf); //serial output
free(buf);
}
}
char *my_strcat(const char *str1, const char *str2) {
char *new_str;
new_str = malloc(strlen(str1)+strlen(str2)+1);
new_str[0] = '\0';
strcat(new_str,str1);
strcat(new_str,str2);
return new_str;
}
串行输出...
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
#INIT.
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123
qweasdzxc123