这个程序适用于输入: "problem"
但停下来: "this is the problem,this is the problem,this is the problem"
为什么?
#include <stdio.h>
int main()
{
char *p;
gets(p);
puts(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有内存保护问题?
你缺少分配内存,将数据读入使用gets(),char * p就像一个指针,指向一个随机地址.
这引发了未定义的行为.任何事情都可能发生,即使只读了一个字符.
事实上,程序不会因为少于26个字符而崩溃,这只是运气不好.
您可以通过例如更改来提供内存
char * p;
Run Code Online (Sandbox Code Playgroud)
成为
char str[42] = {0}; /* = {0} initializes the array to all `0`s. */
char * p = str;
Run Code Online (Sandbox Code Playgroud)
根据urzeit的评论:这使得p指向一个包含42个字符的数组,这本身就足以容纳41个字符的所谓"字符串".第42个字符被重新分配以容纳0-terminator,表示"字符串"的结尾.
注意:gets()是邪恶的,因为程序员没有可能告诉函数缓冲区传递给多少字符gets()是capabale.请fgets()改用.
顺便说一句:int main(void)应该return是int.