《C与指针》第十一章练习
本章问题
1.在你的系统中,你能够声明的静态数组最大的长度能达到多少?使用动态内存分配,你最大能获取的内存块有多少?
answer:
This will vary from system to system,there are several things that may affect the result on PC-based systems,including 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系统分配的结果依赖于swap空间或者其他原因)
2.当你一次请求分配500个字节的内存时,你实际获得的动态分配内存数量总共有多大?请你一次请求分配5000个字节又如何?它们存在区别吗?如果有,你如何解释?
answer:There are two explanations possible,Requesting smaller chunks may allow more memory to be allocated because the amount of memeory 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 overhead of the extra space that malloc attaches to the memory in order to keep track of the size of each allocated chunk.
(可能有两种解释,要求更小的块可能会允许分配更多的内存,因为在最后内存分配剩余的总量会更小,这将会使较小的要求总量更大,也有可能要求更小的分配更小,这是因为额外的空间开销,是malloc附加用来跟踪每块已分配内存的大小的内存)
//linux下可以调用malloc_usable_size函数来获取实际分配的内存
#include <stdio.h>
#include <stdlib.h> int main()
{
char *p;
p = malloc( * sizeof(char));
printf("%u",malloc_usable_size(p));
free(p);
p = malloc( * sizeof(char));
printf("\n%u",malloc_usable_size(p));
free(p);
return ;
}
运行结果:

关于malloc_usable_size函数的具体用法参考:http://man7.org/linux/man-pages/man3/malloc_usable_size.3.html
3.在一个从文件读取字符串的程序中,有没有什么值可以合乎逻辑地作为输入缓冲区的长度?
answer:

如果输入包含在一个文件中,它肯定是由其他程序(例如编辑器)放在那儿的。如果是这种情况,最长行的长度是由编辑器程序支持的,它会作出一个合乎逻辑的选择,确定你的输入缓冲区的大小。
4.有些C编译器提供了一个称为alloca的函数,它与malloc函数的不同之处在于它在堆栈上分配内存,这种类型分配有什么优缺点?
answer:The primary advantage is that the memory will be automatically freed when the function that allocated it returns,this property occurs because of how stacks work,and it guarantees that there will be no memeory leaks,but this behavior is also a disadvantage,because the allocated memory disappears when the function returns,it cannot be used for data that are passed back to the calling program.
(最简单的优点就是当被分配内存的函数返回时,内存可以自动释放,由于堆栈的工作属性,它保障了不会发生内存泄露,但是这也是一个缺点,因为当函数返回时,分配的内存消失了,它不能被数据使用或被调用函数返回)
5.下面的程序用于读取整数,整数的范围在1和从标准输入读取的size之间,它返回每个值出现的次数,这个程序包含了几个错误,你能找出它们吗?


answer:
a 用字面值常量2作为整形值的长度。这个值在整形值长度为2个字节的机器上能正常工作。但在4字节整数的机器上,实际分配的内存将只是所需内存的一半,应该换用sizeof
b 从malloc函数返回的值未被检查,如果内存不足,它将是NULL
c 把指针退到数组左边界的左边来调整下标的范围或许行得通,但它违背了标准关于指针不能越过数组左边界的规定
d 指针经过调整以后,第一个元素的下标变成了1,接着for循环将错误的从0开始,在许多系统中,这个错误将破坏malloc所使用的用于追踪堆的信息,常常导致程序奔溃
e 数组增值前并未检查输入值是否位于合适的范围内,非法的输入值可能会以一种有趣的方式导致程序奔溃
f 如果数组应该返回,它不能被free函数释放
//修改后的函数
#include <stdio.h> int *frequency(int size)
{
int *array;
int i;
array = (int *)malloc(size * sizeof(int)); if(array == NULL)
return NULL; for(i = ; i < size; i++)
array[i] = ; whlie(scanf("%d",&i) == ){
if(i <= && i > size)
return NULL;
array[i - ] += ;
}
return array;
}
6.假定你需要编写一个程序,并希望最大限度的减少堆栈的使用量,动态内存分配能不能对你有所帮助?使用标量数据又如何?
answer:Yes,dynamic allocation will use less stack space because the memory for the arrays will be taken from the heap rather than the stack,Dynamic allocation of scalars will help only if the values being allocated are larger than the size of a pointer,as it would be with a large structure,there is no gain in dynamically allocating an integer because the pointer variable you must have to keep track of it takes just as much space as the integer itself.
(是的,动态分配将会使用更少的堆栈空间因为数组的内存将会从内存堆中获取而不是堆栈,标量的动态分配仅仅在分配的大小远远大于一个指针时才能有所帮助,对一个整形变量使用动态内存分配没有什么好处,因为将会有一个指针变量用来跟踪这个整形变量它自己)
7.在程序11.4b中,删除两个free函数的调用会导致什么结果?

answer:Memory leaks would be possible,but only when either the second or third allocations failed,meanning that the program had nearly run out of memory anyway,
(内存可能会泄露,在第二次或第三次分配失败时,意味着程序的内存被耗尽)
本章练习
1.请你尝试编写calloc函数,函数内部使用malloc函数来获取内存。
answer:
void *mycalloc(size_t num_element, size_t element_size){
int i;
n_element = num_element * element_size;
char *p = malloc(n_element);
if(p == NULL)
return NULL;
for(i = ; i < n_element; i++)
p[i] = ;
return p;
}
2.编写一个函数,从标准输入读取一列整数,把这些值存储于一个动态分配的数组中并返回这个数组,函数通过观察EOF判断输入是否结束,数组的第一个数是数组包含的值的个数,它的后面就是这些整数值。
answer:
#include <stdio.h>
#include <stdlib.h> #define DELTA 100 int *read()
{
int *array;
int count;
int size;
int value; size = DELTA;
count = ;
array = malloc((size + ) * sizeof(int)); if(array == NULL)
return NULL;
while((scanf("%d",&value)) == ){
count++;
if(count >= size){
size += DELTA;
array = realloc(array,(size + ) * sizeof(int));
if(array == NULL)
return NULL;
}
array[count] = value;
} if(count < size){
array = realloc(array,(count + ) * sizeof(int));
if(array == NULL)
return NULL;
}
array[] = count;
return array;
}
这个解决办法里有一个相当不错的技巧,就是预定义的那个DELTA,它相当于一个缓冲区,既不用每次多输入一个数据就要重新申请分一次内存,又保证不会浪费太多的内存,这个解决办法的意思就是说,每次申请DELTA个空间,不够了再添加DELTA个空间,最后发现没有用到的空间再还回去,一个平衡效率和内存浪费之间的解决办法。
3.编写一个函数,从标准输入读取一个字符串,把字符串复制到动态内存分配的内存中,并返回该字符串的拷贝,这个函数不应该对读入字符串的长度作任何限制!
answer:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h> #define DELTA 256 char *readstring()
{
static char *buffer = NULL;
static int buffer_size = ;
int ch;
int len = ;
char *bp = buffer; do{
ch = getchar();
if(ch == '\n' && ch == EOF)
ch = '\0'; if(len > buffer_size){
buffer_size += DELTA;
buffer = realloc(buffer,buffer_size);
assert(buffer != NULL);
bp = buffer + len;
}
*bp++ = ch;
len++;
}while(ch != '\0'); bp = malloc(len);
assert(bp != NULL);
strcpy(bp,buffer);
return bp;
}
4.编写一个程序,按照下图中的样子创建数据结构,最后三个对象都是动态分配的结构。第一个对象则可能是一个静态的指向结构的指针。你不必使这个程序过于全面--我们将在下一章讨论这个结构。

answer:
#include <stdio.h>
#include <stdlib.h> typedef struct LIST{
int data;
struct LIST *link;
}List; List *newlist(int value)
{
List *new;
new = (List *)malloc(sizeof(List));
new->data = value;
return new;
} int main()
{
List *head;
head = newnode();
head->link = newnode();
head->link->link = newnode();
head->link->link->link = NULL;
return ;
}
《C与指针》第十一章练习的更多相关文章
- C和指针 第十一章 习题
1编写calloc,内部使用malloc函数获取内存 #include <stdio.h> #include <stdlib.h> void *myAlloc(unsigned ...
- C和指针 第十一章 动态内存分配
声明数组时,必须指定数组长度,才可以编译,但是如果需要在运行时,指定数组的长度的话,那么就需要动态的分配内存. C函数库stdlib.h提供了两个函数,malloc和free,分别用于执行动态内存分配 ...
- JS复习:第十、十一章
第十章 NodeList是一种类数组对象,用于保存一组有序的节点,可以通过位置来访问这些节点,但它并不是Array实例,将其转化为数组的方法: function converToArray(nodes ...
- 《汇编语言 基于x86处理器》第十一章 MS-DOS 编程部分的代码 part 2
▶ 书中第十一章的程序,主要讲了 Windows 接口,在小黑框中进行程序交互 ● 在屏幕指定位置输出带自定义属性的文字 INCLUDE Irvine32.inc .data outHandle HA ...
- Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第十一章:模板测试
原文:Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第十一章:模板测试 代码工程地址: https://github.co ...
- 第十一章:Python高级编程-协程和异步IO
第十一章:Python高级编程-协程和异步IO Python3高级核心技术97讲 笔记 目录 第十一章:Python高级编程-协程和异步IO 11.1 并发.并行.同步.异步.阻塞.非阻塞 11.2 ...
- 操作系统思考 第十一章 C语言中的信号量
第十一章 C语言中的信号量 作者:Allen B. Downey 原文:Chapter 11 Semaphores in C 译者:飞龙 协议:CC BY-NC-SA 4.0 信号量是学习同步的一个好 ...
- CPrimerPlus第十一章中的“选择排序算法”学习
C Primer Plus第十一章字符串排序程序11.25中,涉及到“选择排序算法”,这也是找工作笔试或面试可能会遇到的题目,下面谈谈自己的理解. 举个例子:对数组num[5]={3,5,2,1,4} ...
- <构建之法>第十一章、十二章有感
十一章:软件设计与实现 工作时要懂得平衡进度和质量.我一直有一个困扰:像我们团队这次做 男神女神配 社区交友网,我负责主页的设计及内容模块,有个队友负责网站的注册和登录模块,有个队友负责搜索模块,有个 ...
- sql 入门经典(第五版) Ryan Stephens 学习笔记 (第六,七,八,九,十章,十一章,十二章)
第六章: 管理数据库事务 事务 是 由第五章 数据操作语言完成的 DML ,是对数据库锁做的一个操作或者修改. 所有事务都有开始和结束 事务可以被保存和撤销 如果事务在中途失败,事务中的任何部分都不 ...
随机推荐
- Loadrunner11安装和破解方法
公司很多项目都在做性能测试,打算把性能测试学习下.(不懂还可以问问公司大神,这么好的机会不要错过了O(∩_∩)O哈哈~)用了二周实践看了性能测试方面一些基本术语和概念,一直都还没自己动手实践,光看基本 ...
- 【转】 Easy RadControl 之 RadGridView(Silverlight)
1.不显示第1列即列指示器(Row Indicators) 在 telerik:RadGridView中设置属性 RowIndicatorVisibility="Collapsed&qu ...
- Request 请求页面的地址路径获取
Request.ApplicationPath: /testweb Request.CurrentExecutionFilePath: /testweb/default.aspx Request.Fi ...
- windows下安装rabbitmq的php扩展amqp
最近研究rabbitmq队列,linux安装这样的软件一向都是很方便的,但是windows可能会比较麻烦,所以对windows的安装做个记录. windows上使用的php扩展为dll文件,首先去下载 ...
- javaScript学习(入门)
不落俗套的来讲讲javascript的特点: 1.所有主流浏览器都是支持javascript的. 2.绝大部分网页都使用javascript. 3.javascript可以实现网页呈现各种动态效果. ...
- Spark源码学习1.3——TaskSetManager.scala
TaskSetManager.scala TaskSet是指一系列被提交的task,一般是代表特定的stage中丢失的partition.TaskSetManager通过一个TaskScheduler ...
- Web测试中常见分享问题
Web测试中,由于开发通常指注重完成H5页面的逻辑功能,对各种系统.浏览器等考虑不周,同时Android端各类机型碎片化,容易产生兼容性问题,这其中以分享类型为最. 本文简单分析总结一些测试 ...
- Longest Increasing Path in a Matrix -- LeetCode 329
Given an integer matrix, find the length of the longest increasing path. From each cell, you can eit ...
- 【Mocha.js 101】钩子函数
前情提要 在上一篇文章<[Mocha.js 101]同步.异步与 Promise>中,我们学会了如何对同步方法.异步回调方法以及 Promise 进行测试. 在本篇文章中,我们将了解到 M ...
- 2014嘉杰信息杯ACM/ICPC湖南程序设计邀请赛暨第六届湘潭市程序设计竞赛
比赛链接: http://202.197.224.59/OnlineJudge2/index.php/Contest/problems/contest_id/36 题目来源: 2014嘉杰信息杯ACM ...