首页 > 其他分享 >操作系统导论习题解答(14. Memory API)

操作系统导论习题解答(14. Memory API)

时间:2022-10-14 19:12:26浏览次数:59  
标签:src malloc int char API Memory 习题 sizeof

Interlude: Memory API

1. Types of Memory

对于一个即将运行的C程序,有两种分配内存的方式。
第一种为stack memory,也叫做automatic memory
当你调用 func(), 编译器做剩下的工作,确保在stack上给变量x分配内存地址。

void func () {
	int x;	// declares an integer on the satck
	...
}

另一种为heap memory,需要你自己直接为变量分配内存并最后进行多余内存清理。

void func () {
	int *x = (int *) malloc (sizeof (int));
	...
}

2. The malloc() Call

double *f = (double *) malloc (sizeof(double)); 

看一下上面这行代码,sizeof() 是在 compile time 运行,而不是 run time,故它不是函数调用。

在使用sizeof()时,你可能不会得到你想要的结果。举个例子:

int *x = malloc (10 * sizeof(int));
printf("%d\n", sizeof(x));

对于上面这两行代码,你可能想给一个数组分配10个整数,你心中想的肯定要返回数组的总大小至少为40字节(不同机器可能对于int大小设置不同)。但是最后返回的可能只有4或8个字节(int类型的大小)。
要达到你的目的,代码应该要写成如下形式:

int x[10];
printf("%d\n", sizeof(x));

还有一种情况你需要注意,就是有string类型存在时。每个string末尾都有一个'/0'字符作为结束,如果用sizeof()得到的结果把最后的结束字符算进去

3. The free() Call

对于你自己手动为变量分配的内存地址,你就有责任当这个变量完成它的任务后释放它的内存地址。

int *x = malloc (10 * sizeof(int));
...
free(x);

4. Common Errors

4.1 Forgetting To Allocate Memory

/* mistake */
char *src = "hello";
char *dst;	// oops! unallocated
strcpy(dst, src);	// segfault and die

// correct
char *src = "hello";
char *dst = (char *) malloc (strlen(src) + 1);
strcpy(dst, src);

4.2 Not Allocating Enough Memory

char *src = "hello";
char *dst = (char *) malloc (strlen(src));	// too small!
strcpy(dst, src);

对于strlen()函数,它返回参数字符串的大小但是未计入参数字符串结尾的'/0'字符

4.3 Forgetting to Initialize Allocated Memory

对于你想使用的每个变量,都最好初始化它的值和地址。

4.4 Free

在释放分配的内存空间时,可能会有以下四个原因造成错误:

  1. Forgetting To Free Memory
  2. Freeing Memory Before You Are Done With It
  3. Freeing Memory Repeatedly
  4. Calling free() Incorrectly

以C++语言为例子,newdelete 成对出现,不能多也不能少。

标签:src,malloc,int,char,API,Memory,习题,sizeof
From: https://www.cnblogs.com/astralcon/p/16792698.html

相关文章