使用指针在C中追加字符串

Leo*_*Leo 2 c string pointers append

对于我的生活,我无法弄清楚为什么这个程序不起作用.我正在尝试使用指针连接两个字符串并继续收到此错误:

a.out(28095) malloc: *** error 
for object 0x101d36e9c: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug
Run Code Online (Sandbox Code Playgroud)

我的str_append.c:

#include <stdio.h>
#include <stdlib.h>
#include "stringlibrary.h"  /* Include the header (not strictly necessary here) */

//appends s to d
void str_append(char *d, char *s){
  int i=0, j=0;

  d = realloc(d, strlength(d)+strlength(s)+1);
  //find the end of d
  while(*(d+i)!='\0'){
    i++;
  }


  //append s to d
  while(*(s+j)!='\0'){
    *(d+i)=*(s+j);
    i++;
    j++;
  }
  *(d+i)='\0';


}
Run Code Online (Sandbox Code Playgroud)

我有自己的strlength函数,我100%肯定有效.

我的主要内容:

#include <stdio.h>
#include <stdlib.h>
#include "stringlibrary.h"

int main(int argc, char **argv)
{
 char* str = (char*)malloc(1000*sizeof(char));
 str = "Hello";
 char* str2 = (char*)malloc(1000*sizeof(char)); 
str2 = " World";

str_append(str, str2);


 printf("Original String: %d\n", strlength(str));
 printf("Appended String: %d\n", strlength(str));


return 0;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试重新分配到临时变量并收到相同的错误.任何帮助表示赞赏.

编辑:谢谢你的所有答案.这个网站太棒了.我不仅知道自己哪里出错了(我猜是简单的错误),但我发现了一个关于字符串的不了解的漏洞.由于我不能使用strcpy函数,我已经实现了自己的.它基本上是strcpy的源代码.

char *string_copy(char *dest, const char *src)
{
 char *result = dest;
 while (*dest++ = *src++);
 return result;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你的问题在这里

char* str = (char*)malloc(1000*sizeof(char));
str = "Hello";
Run Code Online (Sandbox Code Playgroud)

首先,为1000个字符分配空间,并将指针指向该内存的开头.
然后在第二行中,将指针指向一个导致内存泄漏的字符串文字.
指针不再指向分配的内存.
稍后在函数中,您尝试更改只读的字符串文字.