-2

这是适用于输入的程序:"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;
}

有没有内存保护问题?

4

2 回答 2

6

您缺少分配内存,将数据读入 using gets(),这char * p只是一个指向随机地址的指针。

这会引发未定义的行为。任何事情都可能发生,即使只读取 1 个字符。

程序在少于 26 个字符时不会崩溃的事实只是运气不好。

您可以通过例如更改来提供内存

char * p;

成为

char str[42] = {0}; /* = {0} initializes the array to all `0`s. */
char * p = str;

根据urzeit的评论:这使得 p 指向一个由 42 个字符组成的数组,它本身可以容纳一个所谓的 41 个字符的“字符串”。第 42 个字符被保留以保存 -0终止符,表示“字符串”的结尾。


注意:是邪恶的,因为程序员无法告诉函数缓冲区传递给的字符可以容纳gets()多少字符。gets()改为使用fgets()


顺便说一句:int main(void)应该returnint.

于 2013-09-01T07:04:33.500 回答
3

The actual reality is that it's probably "working" for short strings because you're just overwriting your stack, which is memory your program owns, so it doesn't crash. However, this is not "working" by any reasonable definition of the word.

From a C language point of view, all you know is that it's just undefined behavior, it's bad, and you should fix it.

于 2013-09-01T07:17:50.063 回答