嘿,我试图解决这个学校练习..realloc引起的分割错误?
编写一个程序,不断读取字符串并连接它们(将它们添加到单个字符串)。串联应该在函数中发生,如果成功则返回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;
}
欢迎堆栈溢出。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –
解决这些问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –
你可以用'toupper()'或'tolower()'来减少你的'choice'比较,例如:'toupper(choice)=='Y')'。 –