如何才能获得()超过由malloc分配的内存()? [英] How can gets() exceed memory allocated by malloc()?

查看:135
本文介绍了如何才能获得()超过由malloc分配的内存()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在malloc和realloc函数一个疑问,当我使用malloc函数
分配的字符指针10字节的存储器。但是,当我将数值
该字符指针,它需要超过10个字节,如果我尝试分配。它是如何可能的。

I have a doubt in malloc and realloc function, When I am using the malloc function for allocating the memory for the character pointer 10 Bytes. But when I am assigning the value for that character pointer, it takes more than 10 bytes if I try to assign. How it is possible.

例如:

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

该字符串是:你好世界,这是检验

The String is :hello world this is for testing

现在看一下输出的字符数超过10个字节。
这怎么可能,我需要明确的解释。
先谢谢了。

Now look at the output the number of characters are more than 10 bytes. How this is possible, I need clear explanation. Thanks in Advance.

推荐答案

malloc的将预留10个字节(在你的情况假设焦炭已经1个字节),并返回保留区的起点。结果
你做了获得,所以它让你键入的文本和使用指针书写。
在Windows / MAC OS X / UNIX(OS进展'S)已受保护的内存。
这意味着,当你做一个malloc /新操作系统准备金,对你的程序存储区。如果另一个程序试图在这一领域的分段错误是因为你,你不应该写一写的面积来写。

The malloc will reserve 10 bytes (in your case assuming the char have 1 byte) and will return the start point of the reserved area.
You do a gets, so it get the text you typed and write using your pointer. Windows/Mac os x/ Unix (Advances OS'S) have protected memory. That means, when you do a malloc/new the OS reserve that memory area for your program. IF another program tries to write in that area an segmentation fault happens because you wrote on an area that you should not write.

您保留10个字节。
如果字节11,12,13,14还没有留给其他程序也不会崩溃,如果是你的程序将访问保护区和崩溃。

You reserved 10 bytes. IF the byte 11, 12, 13, 14 are not yet reserved for another program it will not crash, if it is your program will access an protected area and crash.

这篇关于如何才能获得()超过由malloc分配的内存()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆