勇芳软件工作室.汉化:  SQLite3 API Functions > Memory Allocation >

sqlite3_malloc

Previous pageReturn to chapter overviewNext page

描述

 

SQLite内核使用sqlite3_mallocsqlite3_reallocsqlite3_free来完成所有内部内存分配需求。前一句中的“核心”不包括操作系统特定的VFS实现。Windows VFS使用原生的malloc自由进行某些操作。

 

sqlite3_malloc函数返回指向内存块的指针,长度至少为N个字节,其中N为参数。如果sqlite3_malloc无法获得足够的可用内存,则返回NULL指针。如果参数N到sqlite3_malloc为零或负,则sqlite3_malloc返回NULL指针。

 

C / C ++语法

 

void *sqlite3_malloc(int);

 

PB语法

 

FUNCTION sqlite3_malloc ( _

BYVAL numBytes AS LONG _

) AS DWORD

 

参数

 

numBytes

 

[in]要分配的字节数

 

返回值

 

指向分配的内存。

 

备注

 

如果使用SQLITE_4_BYTE_ALIGNED_MALLOC编译时选项,则sqlite3_mallocsqlite3_realloc返回的内存总是对齐至少8个字节的边界,或4字节的边界。

 

在SQLite版本3.5.0和3.5.1中,可以定义SQLITE_OMIT_MEMORY_ALLOCATION,这将导致这些功能的内置实现被省略。该函数不再提供。只能使用内置内存分配器。

 

在SQLite版本3.7.10之前,在由SQLite使用的UTF-8编码和任何文件名编码之间转换文件名时,直接称为系统的malloc自由的Windows操作系统界面层由特定的Windows安装使用。检测到内存分配错误,但是它们已报告为SQLITE_CANTOPEN或SQLITE_IOERR,而不是SQLITE_NOMEM。

 

sqlite3_freesqlite3_realloc的指针参数必须为NULL,否则从先前调用sqlite3_mallocsqlite3_realloc获取的指针尚未发布。

 

应用程序在使用sqlite3_freesqlite3_realloc发布后,不得读取或写入内存块的任何部分。

 

C ++实现代码

 

/*

** Allocate memory.  This function is like sqlite3_malloc() except that it

** assumes the memory subsystem has already been initialized.

*/

SQLITE_PRIVATE void *sqlite3Malloc(int n){

void *p;

if( n<=0               /* IMP: R-65312-04917 */

 || n>=0x7fffff00

){

  /* A memory allocation of a number of bytes which is near the maximum

  ** signed integer value might cause an integer overflow inside of the

  ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving

  ** 255 bytes of overhead.  SQLite itself will never use anything near

  ** this amount.  The only way to reach the limit is with sqlite3_malloc() */

  p = 0;

}else if( sqlite3GlobalConfig.bMemstat ){

  sqlite3_mutex_enter(mem0.mutex);

  mallocWithAlarm(n, &p);

  sqlite3_mutex_leave(mem0.mutex);

}else{

  p = sqlite3GlobalConfig.m.xMalloc(n);

}

assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */

return p;

}

 

/*

** This version of the memory allocation is for use by the application.

** First make sure the memory subsystem is initialized, then do the

** allocation.

*/

SQLITE_API void *sqlite3_malloc(int n){

#ifndef SQLITE_OMIT_AUTOINIT

if( sqlite3_initialize() ) return 0;

#endif

return sqlite3Malloc(n);

}