Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 连接字符串时出错_C_Pointers_Realloc - Fatal编程技术网

C 连接字符串时出错

C 连接字符串时出错,c,pointers,realloc,C,Pointers,Realloc,我正在尝试创建一个函数,该函数在一个字符串之后应用另一个字符串。我目睹了以下错误。请帮忙。 *检测到glibc/a.out:realloc():无效的旧大小:0x00007fff7af0d450** //以下代码将原始字符串连接到另一个字符串中 #包括 #包括 #包括 void strcatstring(char*str,char*newstr) { int m=strlen(str); int n=strlen(newstr); newstr=(char*)realloc(newstr,10*

我正在尝试创建一个函数,该函数在一个字符串之后应用另一个字符串。我目睹了以下错误。请帮忙。 *检测到glibc/a.out:realloc():无效的旧大小:0x00007fff7af0d450**

//以下代码将原始字符串连接到另一个字符串中
#包括
#包括
#包括
void strcatstring(char*str,char*newstr)
{
int m=strlen(str);
int n=strlen(newstr);
newstr=(char*)realloc(newstr,10*sizeof(char));
char*newstr1=(char*)malloc(10*sizeof(char));
newstr1=newstr;
而(*newstr!='\0')
{
++newstr;
}
而(*str!='\0')
{
*newstr=*str;
++newstr;
++str;
}
printf(“%s”,newstr1);
}
int main()
{
int n=6;char*str;char str1[10];
str1[0]='y';
str1[1]=“u”;
str=(char*)malloc(n*sizeof(char));
printf(“\n输入字符串\n”);
scanf(“%s”,str);
put(str);
strcatstring(str,str1);
返回0;
}

问题在于,您首先尝试重新分配未分配的内存(按照
realloc
希望的方式)

如果在
main
函数中将
str1
声明为数组,则编译器将在堆栈上而不是在堆上分配此内存。
realloc
函数只能通过
malloc
calloc
或更早的
realloc
调用重新分配堆上分配的内存

如果
realloc
调用可以工作,那么当您分配内存并将其分配给
newstr1
时,就会出现内存泄漏,并在下一行中用
newstr
指针覆盖
newstr1
指针


而且您不应该分配固定的大小,请记住,您将一个大小为
m
的字符串附加到一个大小为
n
的字符串。想想如果
m+n
大于9会发生什么。这导致了下一个问题,即您没有终止结果字符串,因为您没有复制终止的
'\0'
字符。

尝试在调用时将指针传递给指针,如下所示

strcatstring(str,&newstr);

str1
您正在使用的字符串不能以“\0”结尾。您必须手动将该字符放在末尾

无法重新分配堆栈上分配的内存<代码>str1在堆栈上分配

property
strcat()
具有其他顺序的参数。目的地第一

你的命名习惯很糟糕<代码>str<代码>新闻TR?源代码和目的代码怎么样。而且,
m
n
什么也没说。为什么不
sourceLen
destinationLen


strcatstring()
中完成循环后,不要将“\0”字符放在末尾。使用该字符串很可能会出现内存错误。

str1是一个数组,在堆栈上分配
realloc()
必须用于在堆上分配空间的指针。

首先正确缩进代码请查看@Kninnug放置tabsexcellent的位置。关于为什么我使用malloc声明str1时没有错误,您又消除了我的一个疑问。非常感谢您的回复
strcatstring(str,&newstr);