【发布时间】:2017-02-15 20:35:32
【问题描述】:
嘿,我正在尝试解决这个学校练习..
编写一个程序,不断读取字符串并将它们连接起来(将它们添加到单个字符串中)。连接应该发生在一个函数中,如果成功则返回 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;
}
【问题讨论】:
-
欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
您可以使用
toupper()或tolower()来减少choice的比较,例如:toupper(choice) == 'Y')。 -
free(src)- 您尝试在此处释放数组string。另外,*dest=(char*)realloc(NULL,sizeof(*src));- 这会为 1 个char分配空间。 -
您费尽心思寻找新的长度(但忘记了终止符),然后用
*dest=(char*)realloc(NULL,sizeof(*src));将分配1 字节 放在了你的剑上。此外,传递指针变量本身,如果您尚未分配任何内存,则可能带有值NULL。