我在概念上无法理解这个系统调用接近尾声时发生了什么,以及为什么。我知道getstk.c方法返回可用空间的最高内存地址,但不理解一些代码在做什么。对此进行一些澄清将是非常好的。我不完全理解的代码区域用星号强调。
/* getstk.c - getstk */
#include <xinu.h>
/*------------------------------------------------------------------------
* getstk - Allocate stack memory, returning highest word address
*------------------------------------------------------------------------
*/
char *getstk(
uint32 nbytes /* size of memory requested */
)
{
intmask mask; /* saved interrupt mask */
struct memblk *prev, *curr; /* walk through memory list */
struct memblk *fits, *fitsprev; /* record block that fits */
mask = disable();
if (nbytes == 0) {
restore(mask);
return (char *)SYSERR;
}
nbytes = (uint32) roundmb(nbytes); /* use mblock multiples */
prev = &memlist;
curr = memlist.mnext;
fits = NULL;
fitsprev = NULL; /* to avoid a compiler warning */
while (curr != NULL) { /* scan entire list */
if (curr->mlength >= nbytes) { /* record block address */
fits = curr; /* when request fits */
fitsprev = prev;
}
prev = curr;
curr = curr->mnext;
}
if (fits == NULL) { /* no block was found */
restore(mask);
return (char *)SYSERR;
}
if (nbytes == fits->mlength) { /* block is exact match */
fitsprev->mnext = fits->mnext;
**} else { /* remove top section */
fits->mlength -= nbytes;
fits = (struct memblk *)((uint32)fits + fits->mlength);
}**
memlist.mlength -= nbytes;
restore(mask);
**return (char *)((uint32) fits + nbytes - sizeof(uint32));**
}struct memblk可以在这里找到:
struct memblk { /* see roundmb & truncmb */
struct memblk *mnext; /* ptr to next free memory blk */
uint32 mlength; /* size of blk (includes memblk)*/
};
extern struct memblk memlist; /* head of free memory list */为什么他们返回fits + nbytes - sizeof(uint32)?为什么他们要将fits(结构)转换为uint32类型?
发布于 2013-04-27 20:47:31
if (nbytes == fits->mlength) { /* block is exact match */
fitsprev->mnext = fits->mnext;
**} else { /* remove top section */
fits->mlength -= nbytes;
fits = (struct memblk *)((uint32)fits + fits->mlength);
}**
memlist.mlength -= nbytes;
restore(mask);
**return (char *)((uint32) fits + nbytes - sizeof(uint32));**如果找到了一个完美的匹配,该块就会从空闲列表中删除。如果找到更大的块,则将该块拆分为两个块:比原始块小的空闲块nbytes (fits->mlength -= nbytes);以及从新的空闲块(fits = (struct memblk *)((uint32)fits + fits->mlength))开始的已分配的nbytes块,由函数返回。
为什么他们要返回
+ nbytes - sizeof(uint32)?为什么他们要将fits(结构)转换为uint32类型?
由于堆栈在这种情况下向下增长,因此该函数返回指向堆栈顶部的指针,该指针是位于已分配块末尾的字,即:
(uint32)fits /* start of allocated block */ + nbytes /* size of allocated block */ - sizeof(uint32) /* size of a word */对(uint32)的强制转换是使用整数算法而不是指针算法,否则fits+1将生成一个指向sizeof(struct memblk)超出fits的指针。转换为(char *)可能更惯用。
https://stackoverflow.com/questions/16249210
复制相似问题