g_new0

https://developer.gnome.org/glib/2.28/glib-String-Utility-Functions.html#g-ascii-strtoll

 

 

 

1.4 Basic Utilities

(基本函数,这个Utilities不知道如何译,就写成函数吧,因为后面确实在讲函数,嘿嘿……)

为了简化你的程序与C语言以及系统的交互,GLib提供了大量的函数。 要了解GLib的函数处理数据结构部分,请看1.5节。

 

1.4.1 内存管理

如果你使用GLib提供的内存管理例程,它可以避免你处理很多让你头痛的事。 GLib提供了的附加的错误检查与侦测。在下面的表格中为C程序员提供了一个参考。

你可以使用g_malloc(),g_realloc(),g_free()来代替malloc(),realloc(),free(),它们提供了相同的处理方式。为了将申请的内存在使用前清零,你可以使用g_malloc0()。 注意,它的语法看起来像malloc,而不是calloc()。

GLib Function

Corresponding C Function

gpointer g_malloc(gulong n_bytes)

void *malloc(size_t size) with error handling

gpointer g_malloc0(gulong n_bytes)

like malloc(), but initializes memory as in calloc()

gpointer g_try_malloc(gulong n_bytes)

like malloc() without error checking

gpointer g_realloc(gpointer mem, gulong n_bytes)

void *realloc(void *ptr, size_t size) with error checking

gpointer g_try_realloc(gpointer mem, gulong n_bytes)

realloc() without error checking

void g_free(gpointer mem)

void free(void *ptr)

 

 

注意: 如果你有一些特殊的原因要使用函数的返回值的话,你可以使用g_try_malloc()和g_try_realloc(),如果出错的时候,它们会返回NULL。 你可以在某些不是非常关键的地方使用(如某些用来提高性能的额外缓冲区),或者某些测试的时候。

自然,如果你想覆盖GLib的保护机制,你必须要清楚你在做什么。 对大多数程序来说,这些像g_malloc()的普通函数能节约你大量的代码、错误、以及时间。

一般情况下,你没有必要为malloc或g_malloc指定具体的要申请的块的大小。一般都是使用sizeof()来告诉编译器或运行时系统申请某种类型的某个倍数。 为了与数据类型相符,你必须要将malloc()返回值进行强制转换。 强制转换要用大量的括号和星号,所以GLib提供了一些宏,如g_new(),g_new0()以及g_renew()。 下面是一些示例代码。

 

  1. typedef struct _footype footype;  
  2. footype *my_data;  
  3. /* Allocate space for three footype structures (long version) */  
  4. my_data = (footype *) g_malloc(sizeof(footype)*3);  
  5. /* The abbreviated version using g_new */  
  6. my_data = g_new(footype, 3);  
  7. /* To initialize the memory to 0, use g_new0 */  
  8. my_data = g_new0(footype, 3);  
  9. /* Expand this block of memory to four structures (long version) */  
  10. my_data = (footype *) g_realloc(my_data, sizeof(footype)*4);  
  11. /* Shorter version */  
  12. my_data = g_renew(my_data, 4);  

 

 

 

 

在上面的代码段中你可以清楚地看出,g_new()是g_malloc()的简化,g_renew()是g_realloc()的简易形式,g_new0()是g_malloc0()的简易形式。

警告:记住你在使用g_new()时需要一个类型,就像使用sizeof()一样。 有时候像这样的的语句会产生编译错误:

b = g_new(a, 1) (a只是一个变量,而不是类型)

产生错误的原因就是因为g_new只是一个宏,应该给它传递类型,而不是某个类型的变量。

posted @ 2011-12-12 16:56  alxe_yu  阅读(2408)  评论(0)    收藏  举报