Hei, 나는이 학교 운동을 해결하려고 노력했다.Realloc으로 인한 세그먼트 오류?
문자열을 읽고 계속 읽는 프로그램을 작성하여 단일 문자열에 추가한다. 연결은 성공하면 1을 반환하고 실패하면 0을 반환하는 함수에서 수행되어야합니다. 메모리 할당을 위해서만 realloc을 사용하십시오!
프로그램을 디버깅하는 동안 오류가 발생하지 않지만 문자열을 삽입 한 후 프로그램을 실행하려고하면 "세그멘테이션 오류"가 표시 될 수 있습니다.
1) 당신은 힙에 자신을 할당 free
해야 것만 : 코드 적어도 5 문제가 있습니다
#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)를 읽으신 후 [Help Center] (http://stackoverflow.com/help/asking)의 자료를 참조하십시오. 여기에 물어보십시오. –
이러한 문제를 해결하는 올바른 도구는 디버거입니다.스택 오버플로를 묻기 전에 코드를 단계별로 실행해야합니다. 자세한 도움말은 [작은 프로그램 디버깅 방법 (Eric Lippert 작성)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 참조하십시오. 문제를 재현하는 [최소, 완료 및 확인 가능] (http://stackoverflow.com/help/mcve) 예제와 함께 해당 질문을 \ [편집]해야합니다. 디버거. –
'toupper (choice) == 'Y')'와 같이 toupper() 또는 tolower()를 사용하여'choice'를 비교할 수 있습니다. –