realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.
unsigned char buf[USBEPFIFO_SIZE]; /* data buffer itself */
};
struct usb_endpoint { int type; /* endpoint type: BULKIN, BULKOUT, CTL, ISO ... */
int qlen; /* queue length */
xQueueHandle lock; /* semaphore lock */
xQueueHandle q; /* data queue (pointer of bulk_buf) */
int idx; /* endpoint index */
int epx; /* endpoint mark bit */
int cfg; /* endpoint configure */
int bank; /* current operation bank (for ping-pong mode) */
int txCount; /* used for ping-pong mode *//* endpoint data process function */void (*ep_process) (struct usb_device *dev, struct usb_endpoint *ep, xISRStatus *pxMessage);
};
struct usb_descriptor {
int type; /* descriptor type: device, conf, string or endpoint */
int idx; /* descriptor index (for string descriptor) */
int size; /* descriptor size */
void * data; /* descriptor data */
struct list_head list; /* link list of descriptors */
};
struct usb_deviceOps {
int (*init)(struct usb_device *dev); /* called when framework init usb device, add device descriptors, init private data ... etc. */
int (*reset)(struct usb_device *dev); /* called when reseted by host */
int (*switch_in)(struct usb_device *dev); /* called when switch in */
int (*switch_out)(struct usb_device *dev); /* called when swithc out *//* called when HOST request class interface data */
void (*class_interface_req)(struct usb_device *dev, xUSB_REQUEST *pxRequest); /* called when HOST complete the data sending stage */int (*ctl_data_comp)(struct usb_device *dev, xCONTROL_MESSAGE *pxMessage);
xQueueHandle ready; /* notify this queue when usb device ready */
void *private; /* device private data */
struct list_head list; /* link list of usb device */
};
struct usb_device;
struct usb_ctl;
struct usb_iobuf {
int len; /* data length in the buffer */
unsigned char buf[USBEPFIFO_SIZE]; /* data buffer itself */
};
struct usb_endpoint { int type; /* endpoint type: BULKIN, BULKOUT, CTL, ISO ... */
int qlen; /* queue length */
xQueueHandle lock; /* semaphore lock */
xQueueHandle q; /* data queue (pointer of bulk_buf) */
int idx; /* endpoint index */
int epx; /* endpoint mark bit */
int cfg; /* endpoint configure */
int bank; /* current operation bank (for ping-pong mode) */
int txCount; /* used for ping-pong mode */ /* endpoint data process function */ void (*ep_process) (struct usb_device *dev, struct usb_endpoint *ep, xISRStatus *pxMessage);
};
struct usb_descriptor {
int type; /* descriptor type: device, conf, string or endpoint */
int idx; /* descriptor index (for string descriptor) */
int size; /* descriptor size */
void * data; /* descriptor data */
struct list_head list; /* link list of descriptors */
};
struct usb_deviceOps {
int (*init)(struct usb_device *dev); /* called when framework init usb device, add device descriptors, init private data ... etc. */
int (*reset)(struct usb_device *dev); /* called when reseted by host */
int (*switch_in)(struct usb_device *dev); /* called when switch in */
int (*switch_out)(struct usb_device *dev); /* called when swithc out */ /* called when HOST request class interface data */
void (*class_interface_req)(struct usb_device *dev, xUSB_REQUEST *pxRequest); /* called when HOST complete the data sending stage */ int (*ctl_data_comp)(struct usb_device *dev, xCONTROL_MESSAGE *pxMessage);
};
struct usb_ctlOps {
void (*ctl_transmit_null)(struct usb_ctl *ctl);
void (*ctl_send_stall)(struct usb_ctl *ctl);
void (*ctl_reset_ep0)(struct usb_ctl *ctl);
void (*ctl_detach_usb)(struct usb_ctl *ctl);
void (*ctl_attach_usb)(struct usb_ctl *ctl);
void (*ctl_send_data)(struct usb_ctl *ctl, unsigned char *data,
int req_len,
int send_len,
int is_des);
};
struct usb_ctl {
int addr; /* address alloced by host */
int conf; /* configuration set by host */
eDRIVER_STATE state; /* current status */
xCONTROL_MESSAGE tx; /* control transmit message */
xCONTROL_MESSAGE rx; /* control receive message */
struct ubufm *bufmn; /* 'usb_iobuf' buffer manager, shared by all usb devices */
int prio; /* the main task priority */
xTaskHandle task_handle; /* the main task handler */
struct usb_ctlOps *ctlOps; /* control endpoint operations */
};
struct usb_device {
char name[16]; /* device name, e.g. "usbser" */
struct usb_deviceOps *ops; /* usb device callback functions */
struct usb_ctl *ctl; /* usb control enpoint, provided by framework */
struct list_head desc_list; /* usb descriptors */
struct usb_endpoint *ep[MAX_ENDPOINTS]; /* endpoints */
int active; /* whether the device is active */
xQueueHandle ready; /* notify this queue when usb device ready */
void *private; /* device private data */
struct list_head list; /* link list of usb device */
};
void *private; /* endpoint private data (hardware relevant) */
};
struct usb_endpoint {
int type; /* endpoint type: BULKIN, BULKOUT, CTL, ISO ... */
int qlen; /* queue length */
xQueueHandle lock; /* semaphore lock */
xQueueHandle q; /* data queue (pointer of bulk_buf) */
int idx; /* endpoint index */
/* endpoint data process function */
void (*ep_process)(struct usb_device *dev, struct usb_endpoint *ep, xISRStatus *pxMessage);
void *private; /* endpoint private data (hardware relevant) */
};
tips: 用C表达的一个关键处就是要很好地应用struct来描述模型。
实现OO的继承机制
OO Programing in C is not only POSSIBLE but also PRACTICAL
--------------------------------------------------------------------------------
OO的一个亮点是类的"继承",通过"继承",可以重用许多代码。而且"继承"也是现实生活中非常自然的一种关系。但是很不幸,C没有class,更没有提供"继承"的表达方式。既然能用C的struct来仿真class, 那能不能继续来仿真"继承"呢?答案是:possible。就像<<Inside the C++ Object Modal>>书中所叙述的那样——你可以用C来达到所有C++能做到的事。但这种仿真显然毫无实际应用价值。
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
......
....
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
.....
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
......
其中 container_of 宏如下:
C代码
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
内存管理是计算机编程最为基本的领域之一。在很多脚本语言中,您不必担心内存是如何管理的,这并不能使得内存管理的重要性有一点点降低。对实际编程来说,理解您的内存管理器的能力与局限性至关重要。在大部分系统语言中,比如 C 和 C++,您必须进行内存管理。本文将介绍手工的、半手工的以及自动的内存管理实践的基本概念。
追溯到在 Apple II 上进行汇编语言编程的时代,那时内存管理还不是个大问题。您实际上在运行整个系统。系统有多少内存,您就有多少内存。您甚至不必费心思去弄明白它有多少内存,因为每一台机器的内存数量都相同。所以,如果内存需要非常固定,那么您只需要选择一个内存范围并使用它即可。
/* Include the sbrk function */
#include <unistd.h>
void malloc_init()
{
/* grab the last valid address from the OS */
last_valid_address = sbrk(0);
/* we don't have any memory to manage yet, so
*just set the beginning to be last_valid_address
*/
managed_memory_start = last_valid_address;
/* Okay, we're initialized and ready to go */
has_initialized = 1;
}
void free(void *firstbyte) {
struct mem_control_block *mcb;
/* Backup from the given pointer to find the
* mem_control_block
*/
mcb = firstbyte - sizeof(struct mem_control_block);
/* Mark the block as being available */
mcb->is_available = 1;
/* That's It! We're done. */
return;
}
1. If our allocator has not been initialized, initialize it.
2. Add sizeof(struct mem_control_block) to the size requested.
3. start at managed_memory_start.
4. Are we at last_valid address?
5. If we are:
A. We didn't find any existing space that was large enough
-- ask the operating system for more and return that.
6. Otherwise:
A. Is the current space available (check is_available from
the mem_control_block)?
B. If it is:
i) Is it large enough (check "size" from the
mem_control_block)?
ii) If so:
a. Mark it as unavailable
b. Move past mem_control_block and return the
pointer
iii) Otherwise:
a. Move forward "size" bytes
b. Go back go step 4
C. Otherwise:
i) Move forward "size" bytes
ii) Go back to step 4
void *malloc(long numbytes) {
/* Holds where we are looking in memory */
void *current_location;
/* This is the same as current_location, but cast to a
* memory_control_block
*/
struct mem_control_block *current_location_mcb;
/* This is the memory location we will return. It will
* be set to 0 until we find something suitable
*/
void *memory_location;
/* Initialize if we haven't already done so */
if(! has_initialized) {
malloc_init();
}
/* The memory we search for has to include the memory
* control block, but the users of malloc don't need
* to know this, so we'll just add it in for them.
*/
numbytes = numbytes + sizeof(struct mem_control_block);
/* Set memory_location to 0 until we find a suitable
* location
*/
memory_location = 0;
/* Begin searching at the start of managed memory */
current_location = managed_memory_start;
/* Keep going until we have searched all allocated space */
while(current_location != last_valid_address)
{
/* current_location and current_location_mcb point
* to the same address. However, current_location_mcb
* is of the correct type, so we can use it as a struct.
* current_location is a void pointer so we can use it
* to calculate addresses.
*/
current_location_mcb =
(struct mem_control_block *)current_location;
if(current_location_mcb->is_available)
{
if(current_location_mcb->size >= numbytes)
{
/* Woohoo! We've found an open,
* appropriately-size location.
*/
/* It is no longer available */
current_location_mcb->is_available = 0;
/* We own it */
memory_location = current_location;
/* Leave the loop */
break;
}
}
/* If we made it here, it's because the Current memory
* block not suitable; move to the next one
*/
current_location = current_location +
current_location_mcb->size;
}
/* If we still don't have a valid location, we'll
* have to ask the operating system for more memory
*/
if(! memory_location)
{
/* Move the program break numbytes further */
sbrk(numbytes);
/* The new memory will be where the last valid
* address left off
*/
memory_location = last_valid_address;
/* We'll move the last valid address forward
* numbytes
*/
last_valid_address = last_valid_address + numbytes;
/* We need to initialize the mem_control_block */
current_location_mcb = memory_location;
current_location_mcb->is_available = 0;
current_location_mcb->size = numbytes;
}
/* Now, no matter what (well, except for error conditions),
* memory_location has the address of the memory, including
* the mem_control_block
*/
/* Move the pointer past the mem_control_block */
memory_location = memory_location + sizeof(struct mem_control_block);
/* Return the pointer */
return memory_location;
}
众多可用的分配程序中最有名的就是上述这些分配程序。如果您的程序有特别的分配需求,那么您可能更愿意编写一个定制的能匹配您的程序内存分配方式的分配程序。不过,如果不熟悉分配程序的设计,那么定制分配程序通常会带来比它们解决的问题更多的问题。要获得关于该主题的适当的介绍,请参阅 Donald Knuth 撰写的 The Art of Computer Programming Volume 1: Fundamental Algorithms 中的第 2.5 节“Dynamic Storage Allocation”(请参阅 参考资料中的链接)。它有点过时,因为它没有考虑虚拟内存环境,不过大部分算法都是基于前面给出的函数。
在 C++ 中,通过重载 operator new(),您可以以每个类或者每个模板为单位实现自己的分配程序。在 Andrei Alexandrescu 撰写的 Modern C++ Design 的第 4 章(“Small Object Allocation”)中,描述了一个小对象分配程序(请参阅 参考资料中的链接)。
欢迎进入内存这片雷区。伟大的Bill Gates 曾经失言:
640K ought to be enough for everybody
— Bill Gates 1981
程序员们经常编写内存管理程序,往往提心吊胆。如果不想触雷,唯一的解决办法就是发现所有潜伏的地雷并且排除它们,躲是躲不了的。本章的内容比一般教科书的要深入得多,读者需细心阅读,做到真正地通晓内存管理。
7.1内存分配方式
内存分配方式有三种:
(1) 从静态存储区域分配。内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在。例如全局变量,static变量。
(2) 在栈上创建。在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。
(3) 从堆上分配,亦称动态内存分配。程序在运行的时候用malloc或new申请任意多少的内存,程序员自己负责在何时用free或delete释放内存。动态内存的生存期由我们决定,使用非常灵活,但问题也最多。
7.2常见的内存错误及其对策
发生内存错误是件非常麻烦的事情。编译器不能自动发现这些错误,通常是在程序运行时才能捕捉到。而这些错误大多没有明显的症状,时隐时现,增加了改错的难度。有时用户怒气冲冲地把你找来,程序却没有发生任何问题,你一走,错误又发作了。
常见的内存错误及其对策如下:
u 内存分配未成功,却使用了它。
编程新手常犯这种错误,因为他们没有意识到内存分配会不成功。常用解决办法是,在使用内存之前检查指针是否为NULL。如果指针p是函数的参数,那么在函数的入口处用assert(p!=NULL)进行检查。如果是用malloc或new来申请内存,应该用if(p==NULL) 或if(p!=NULL)进行防错处理。
u 内存分配虽然成功,但是尚未初始化就引用它。
犯这种错误主要有两个起因:一是没有初始化的观念;二是误以为内存的缺省初值全为零,导致引用初值错误(例如数组)。
内存的缺省初值究竟是什么并没有统一的标准,尽管有些时候为零值,我们宁可信其无不可信其有。所以无论用何种方式创建数组,都别忘了赋初值,即便是赋零值也不可省略,不要嫌麻烦。
u 内存分配成功并且已经初始化,但操作越过了内存的边界。
例如在使用数组时经常发生下标“多1”或者“少1”的操作。特别是在for循环语句中,循环次数很容易搞错,导致数组操作越界。
u 忘记了释放内存,造成内存泄露。
含有这种错误的函数每被调用一次就丢失一块内存。刚开始时系统的内存充足,你看不到错误。终有一次程序突然死掉,系统出现提示:内存耗尽。
动态内存的申请与释放必须配对,程序中malloc与free的使用次数一定要相同,否则肯定有错误(new/delete同理)。
u 释放了内存却继续使用它。
有三种情况:
(1)程序中的对象调用关系过于复杂,实在难以搞清楚某个对象究竟是否已经释放了内存,此时应该重新设计数据结构,从根本上解决对象管理的混乱局面。
(2)函数的return语句写错了,注意不要返回指向“栈内存”的“指针”或者“引用”,因为该内存在函数体结束时被自动销毁。
(3)使用free或delete释放了内存后,没有将指针设置为NULL。导致产生“野指针”。
l 【规则7-2-1】用malloc或new申请内存之后,应该立即检查指针值是否为NULL。防止使用指针值为NULL的内存。
l 【规则7-2-2】不要忘记为数组和动态内存赋初值。防止将未被初始化的内存作为右值使用。
l 【规则7-2-3】避免数组或指针的下标越界,特别要当心发生“多1”或者“少1”操作。
l 【规则7-2-4】动态内存的申请与释放必须配对,防止内存泄漏。
l 【规则7-2-5】用free或delete释放了内存之后,立即将指针设置为NULL,防止产生“野指针”。