我对malloc和realloc函数有些疑惑。当我使用malloc函数为字符指针分配10个字节的内存时,但当我尝试为该字符指针分配值时,如果我赋值的内容超过10个字节,它应该不可能成功吧。
例如:
main()
{
char *ptr;
ptr=malloc(10*sizeof(char));
gets("%s",ptr);
printf("The String is :%s",ptr);
}
样例输出:
$./a.out
hello world this is for testing
字符串为:hello world this is for testing
现在看一下输出,字符数超过了10个字节。这是怎么可能的?我需要一个清晰的解释。谢谢!
gets
的问题,不是关于malloc
的。 - Nathan Fellmanmalloc()
的返回值强制转换。 - unwindgets("%s",ptr);
不是对gets
函数的有效调用。gets
的声明为char *gets(char *);
,它只接受一个参数,即指向缓冲区的指针。问题中的代码是否为实际编译和执行的代码? - Eric Postpischil