C和指针课后问答题答案翻译

第11章 动态内存分配

1.在你的系统中,你能够声明的静态数组最大长度能达到多少?使用动态内存分配,你最大能够获取的内存块有多大?

英文答案原文:

This will vary from system to system.There are several things that may affect the result on PC-based systems, includeing the memory model in use, the amount of space in the data and/or stack segment, the amount of available memory on the system, and so forth. The result on Unix systems will depend on the amount of available swap space, among other things.

答案中文翻译:

根据系统不同而值不同。以下是影响基于PC系统的因素:使用的内存模式、数据段或栈段的空闲量、系统上可用内存量等。Unix系统上,取决于可用的交换空间大小。

2.当你一次请求分配500个字节的内存时,实际上获得的动态分配的内存数量总共有多大?当你一次请求分配5000个字节时又如何?它们存在区别吗?如果有,你如何解释?

英文答案原文:

There are two explanations possible.Requesting smaller chunks may allow more memory to be allocated because the amount of memory left over after the last allocation will be smaller.This would make the total for the smaller requests larger.More likely, though,is that the total for the smaller requests is smaller:this is due to the overheed of the extra space that malloc attache to the memory in order to keep track of the size of each allocated chunk.

答案中文翻译:

可能会有两种解释。申请更小的数据块会使得更多的内存得到分配,因为上一次分配剩余的内存大小会变得更小。这将使较小的请求的总数更大。更多的情况是,实际获得的内存数量更大,因为会分配额外的头部空间用于追踪每个被分配的数据块的大小。

4.有些C编译器提供了一个称为alloca的函数,它与malloc函数的不同之处在于它在堆栈上分配内存。这种类型的分配有什么优点和缺点?

主要优点是当分配内存的函数返回时,这块内存会被自动释放。这个属性是由于堆栈的工作方式决定的,它可以保证不会出现内存泄漏。但这种方法也存在缺点。由于当函数返回时被分配的内存将消失,所以它不能用于存储那些回传给调用程序的数据。

6.当你需要编写一个程序,并希望最大限度地减少堆栈的使用量。动态内存分配能不能对你有所帮助?使用标准数据又该如何?

Yes,dynamic allocation will use less stack space because the memory for the arrays will be taken from the heap tather than stack.Dynamic allocation of scalar will help only if the values being allocated are larger than the size of a pointer,as it wold be with a large structures.There is no gain in dynamically allocation an integer because the pointer variable you must have to keep track of it takes just as much space as the integer itself,

7.删除两个free函数的调用会导致什么后果?

英文答案原文:

Memory leeks would be possible,but only when either the second or third allocations failed,meaning that the program had neerl run out of memory anyway.

答案中文翻译:

内存泄漏是可能的, 但只有当第二个或第三次分配失败时, 这意味着程序几乎用尽了内存。

posted @ 2018-10-18 10:34  快乐工作快乐玩  阅读(1035)  评论(0编辑  收藏  举报