realloc引起的分段错误?

Ste*_*tre 1 c realloc dma

嘿,我正试图解决这个学校的运动..

编写一个程序,继续读取字符串并连接它们(将它们添加到单个字符串).串联应该在一个函数中发生,如果成功则返回1,如果失败则返回0.对于内存分配,只使用realloc!

调试程序时我没有收到任何错误,但是当我尝试运行程序时,在插入字符串之后,唯一出现的是"Segmentation Fault",它会是什么?这是代码:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int cat(char **, char *);

int main(void)
{
  char string[51];
  char *output=NULL;
  char choice;
  do
  {
    printf("Please enter a string [<50 chars]: ");
    fgets(string,50,stdin);
    if(string[strlen(string)-1]=='\n') /* if newline was read as well */
      string[strlen(string)-1]=0;      /* discard it */
    if(cat(&output,string))
      printf("\n\nThe string now contains:\n%s\n",output);
    else
    {
      printf("error: memory (re-)allocation failed!\n\n");
      return 1; /* exit with error */ 
    }
    printf("Continue? (y/n) - ");
    fgets(string,3,stdin); /* read input from keyboard - leave a safety buffer to account for read newline */
    choice=string[0]; /* use the first character from the previous read as the choice */
  } while(choice=='y' || choice=='Y');

  free(output);
  return 0;
}

int cat(char **dest, char *src)
{

  int i;
  int length1=strlen(src);
  int length2=strlen(*dest);
  int length3=length1+length2;
  *dest=(char*)realloc(NULL,sizeof(*src));
  printf("%p", *dest);
  if(*dest==NULL) return 0; /* if allocation failed */
  for(i=0;i<=length3;i++)
  {
      if(i<=length1)
        (*dest)[i]=(*dest)[i];
      else
        (*dest)[i]=(src)[i];
  }
  free(src);
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

rus*_*tyx 5

您的代码至少有5个问题:

1)你应该free只在堆上自己分配的内容.不要free(src)因为你传递的内容src指向堆栈内存(char string[51];自动释放).

2)你可能打算重新分配dest,3)你打算分配大小为length3(+ 1 null-terminator)的内存.

    *dest=(char*)realloc(*dest, length3 + 1);
Run Code Online (Sandbox Code Playgroud)

4)最初为NULL strlen(*dest)时会崩溃*dest.

    int length2=(*dest)?strlen(*dest):0;
Run Code Online (Sandbox Code Playgroud)

5)我不认为你的for循环是正确的.它不会连接字符串,您的偏移计算是关闭的.