gpt4 book ai didi

c - 如果输入很大,程序会异常终止

转载 作者:行者123 更新时间:2023-11-30 16:00:27 25 4
gpt4 key购买 nike

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

#define n ((sizeof(char)) * 100 )

int stringlength(char * str)
{
int count=0;
while(*str)
{
if(*str == '\n')
{
*str=0;
}
else
count++, str++;
}
return count;
}


int palin1(char *str, int k)
{
char * pend = str + k - 1;
if(*pend != *str)
return 0;
else
palin1(str+1, k-1);
return 1;
}

int palin(char *str)
{
int length = stringlength(str), f=0;
char *pend = str + length - 1;
while(str <= pend)
{
if(*str == *pend) f=1;
else
return (f = 0);
str++, pend--;
}
return 1;
}

main()
{
char * ps = (char *)malloc(n);
int flag;
if(ps == NULL) printf("Malloc Fail\n");
else
{
printf("Malloc Succeeded, you have memory of %d bytes\n", n);
printf("This program checks if String is Palindrome or not\n\
\nEnter your String: ");
fgets(ps, 100, stdin);
printf("You entered: %s of length %d", ps, stringlength(ps));
int i = 0;
printf("\n\nEnter:\n1.Using iteration\n2.Using Recursion ");
scanf("%d", &i);
switch(i)
{
case 1:
flag=palin(ps);
break;
case 2:
flag=palin1(ps,stringlength(ps));
break;
default:
printf("Invalid input");
}

if(flag) printf("\nYou entered a Palindrome");
else printf("\nNot a Palindrome");
}
free (ps);
return 0;
}

为什么上面的程序 http://www.ideone.com/qpGxi输入时不给出任何输出:

mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

我知道 fgets(ps,100,stdin) 只需要 100 个字符,不会超过这个数字,但为什么程序会停止执行?

最佳答案

您应该检查fgets失败,按照 fgets spec 的建议.

if ( fgets(ps,100,stdin) == NULL ) {
printf("Input failed.");
//check for 'feof' or 'ferror' here
return -1;
}
printf("You entered: %s of length %d",ps,stringlength(ps));

我不明白为什么 fgets会失败,但你会得到一个未初始化的字符缓冲区,这会崩溃 printf .

编辑:您也应该真正注意编译器警告。

prog.c:49: warning: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:59: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
prog.c:63: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
prog.c: In function ‘palin’:
prog.c:46: warning: control reaches end of non-void function
prog.c: In function ‘main’:
prog.c:52: warning: ‘flag’ may be used uninitialized in this function

您可以看到,甚至您的编译器也建议检查 fgets为空。另外,flag应设置为0在默认情况下,否则如果用户输入 1 以外的内容,您将得到未定义的行为或2 .

编辑 2:哦,天哪!你的程序运行良好!您忘记在 Ideone 中检查“运行程序”!!!

http://www.ideone.com/7ecZd

关于c - 如果输入很大,程序会异常终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com